15,471
社区成员
发帖
与我相关
我的任务
分享
DWORD WINAPI ThreadFun(LPVOID threadParam)
{
int n = (int)threadParam;
for (int i=0; i<n; i++)
{
Sleep(1000);
}
printf("thread %d quit.\n", n);
return 0;
}
void WaitForThreadQuit(HANDLE hTheads[], int threadCount)
{
MSG msg;
while(threadCount > 0)
{
DWORD dRet = MsgWaitForMultipleObjects(threadCount,hTheads,FALSE,INFINITE,QS_ALLINPUT);
if (dRet == (WAIT_OBJECT_0 + threadCount))
{
while (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else if ((dRet>=WAIT_OBJECT_0) && (dRet<WAIT_OBJECT_0 + threadCount))
{
int quitIndex = dRet - WAIT_OBJECT_0;
printf("hTheads[%d] quit.\n", quitIndex);
HANDLE hThread = hTheads[quitIndex];
hTheads[quitIndex] = hTheads[--threadCount];
hTheads[threadCount] = hThread;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
const int threadCount = 6;
HANDLE hThreads[threadCount] = {0};
for (int i=0; i<threadCount; i++)
{
hThreads[i] = CreateThread(NULL, 0, ThreadFun, (LPVOID)(i+1), 0, NULL);
}
WaitForThreadQuit(hThreads, threadCount);
printf("all thread quit.\n");
return 0;
}