WaitForSingleObjects对于Thread数组来说相当于busy loop,因为假设结束顺序和创建顺序是一样的.这就带来了效率问题
/*
written by c4pt0r
for studing WaitForMultipleObjects
*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
DWORD WINAPI ThreadFunc(LPVOID);
#define THREAD_POOL_SIZE 3
#define MAX_THREAD_INDEX THREAD_POOL_SIZE-1
#define NUM_TASK 6
int main()
{
HANDLE hThread[THREAD_POOL_SIZE];
int slot=0;
DWORD threadID;
int i;
DWORD exitcode;
for (i=1;i<=NUM_TASK;i++)
{
if (i > THREAD_POOL_SIZE) //if the number of the running thread is more than the pool size,then we wait
{
int rc=WaitForMultipleObjects(THREAD_POOL_SIZE,hThread,false,INFINITE);
slot=rc - WAIT_OBJECT_0 ;
printf("slot %d terminated!\n",slot);
}
hThread[slot++]=CreateThread(NULL,0,ThreadFunc,(LPVOID)slot,NULL,&threadID);
printf("Launch %d \n",slot);
}
WaitForMultipleObjects(THREAD_POOL_SIZE,hThread,true,INFINITE); //the main thread,wait for every thread
for (slot=0 ; slot<THREAD_POOL_SIZE ; slot++)
CloseHandle(hThread[slot]);
printf("All thread terminated!\n");
return EXIT_SUCCESS;
}
DWORD WINAPI ThreadFunc(LPVOID n)
{
srand(GetTickCount());
Sleep((rand()%8*500)+500);
printf("Slot %d idle\n",n);
return (DWORD)n;
}