有一段程序,只能等待前一个线程运行结束,按一次键(_getch)后才能启动下一个线程继续运行。如何能使5个线程并发的执行,没有运行上的依赖关系?请教大家,谢谢!#include <windows.h>
#include <conio.h>DWORD WINAPI ThreadFunc( LPVOID lpParam )
{
ShellExecute(NULL, "open", "d:\\1.exe", NULL, NULL, SW_SHOW); return 0;
}
VOID main( VOID )
{
DWORD dwThreadId, dwThrdParam;
HANDLE hThread;
char szMsg[80]; for (int i = 0; i < 5; i++)
{
hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
// Check the return value for success.
if (hThread == NULL)
{
wsprintf( szMsg, "CreateThread failed." );
MessageBox( NULL, szMsg, "main", MB_OK );
}
else
{
//Sleep
_getch();
CloseHandle( hThread );
}
}
}
#include <conio.h>DWORD WINAPI ThreadFunc( LPVOID lpParam )
{
ShellExecute(NULL, "open", "d:\\1.exe", NULL, NULL, SW_SHOW); return 0;
}
VOID main( VOID )
{
DWORD dwThreadId, dwThrdParam;
HANDLE hThread;
char szMsg[80]; for (int i = 0; i < 5; i++)
{
hThread = CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
// Check the return value for success.
if (hThread == NULL)
{
wsprintf( szMsg, "CreateThread failed." );
MessageBox( NULL, szMsg, "main", MB_OK );
}
else
{
//Sleep
_getch();
CloseHandle( hThread );
}
}
}
和WaitForSingleObject
{
DWORD dwThreadId, dwThrdParam;
HANDLE hThread[5];
char szMsg[80]; for (int i = 0; i < 5; i++)
{
hThread[i]= CreateThread(
NULL, // default security attributes
0, // use default stack size
ThreadFunc, // thread function
&dwThrdParam, // argument to thread function
0, // use default creation flags
&dwThreadId); // returns the thread identifier
// Check the return value for success.
if (hThread[i]== NULL)
{
//i thread failed-----------------------------
wsprintf( szMsg, "CreateThread failed." );
MessageBox( NULL, szMsg, "main", MB_OK );
}
}
_getch(); for(i=0;i<5;i++)
CloseHandle( hThread[i] );
}
如果我不想用_getch()这么蛮横的方法来等待线程启动好,是不是要用到wait一类的方法让进程阻塞?还有能不能同样给个例子,谢谢了!
2 单CPU中绝对的同时启动线程是绝对的做不到,如果你想控制什么时候启动一个线程,你可以在CreateThread时用CREATE—SUSPEND (挂起) --针对你说的“让进程阻塞”
3 “如果我不想用_getch()这么蛮横的方法来等待线程启动好”只要你的CreateThread返回了,就说明已经启动好了或是Create(挂起)好了,所以不用等待了(要么失败,要么成功)4 如果涉及同步问题的话,就要提到:mutex,event,信号量等对象了
功能上比waitsingleobject强 也很好用 采用异步模式读取
CreatThread调用后
还需要调用_afxbeginthread
这样就可以解决问题了
具体的可以参考《VC++6.0技术内幕》里面的关于线程的讲解
《深入浅出MFC——第二版》里面有更详细的讲解