#define THREAD_POOL_SIZE 3 //线程数目
#define NUM_TASKS 6 //任务数目
int main()
{
HANDLE hThrds[THREAD_POOL_SIZE];
int slot = 0;
DWORD threadId;
int i;
DWORD rc;
for (i=0; i < NUM_TASKS; i++)
{
Sleep(1000);
/* Until we've used all threads in *
* the pool, do not need to wait *
* for one to exit */
if (i >= THREAD_POOL_SIZE)
{
/* Wait for one thread to terminate */
rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, FALSE, INFINITE );
slot = rc - WAIT_OBJECT_0;//0 to THREAD_POOL_SIZE -1
if (slot >= 0 && slot < THREAD_POOL_SIZE)
{
printf("Slot %d terminated\n", slot );
}
else
{
printf("Error or Timeout!\n");
return 0;
}
if (hThrds[slot])
{
CloseHandle(hThrds[slot]);
hThrds[slot] = NULL;
}
}
/* Create a new thread in the given
* available slot */
//when slot is THREAD_POOL_SIZE, i is THREAD_POOL_SIZE too.
//slot will be re-assigned between 0 to THREAD_POOL_SIZE -1.
hThrds[slot++] = CreateThread(NULL, 0, ThreadFunc, (LPVOID)slot, 0, &threadId);
printf("Launched thread #%d (slot %d)\n", i, slot);
}
/* Now wait for all threads to terminate */
rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, TRUE, INFINITE );
if (rc >= WAIT_OBJECT_0 && rc < WAIT_OBJECT_0 + THREAD_POOL_SIZE)
{
printf("All threads have terminated\n");
}
else
{
printf("Error or Timeout!\n");
}
for (slot=0; slot<THREAD_POOL_SIZE; slot++)
{
if (hThrds[slot])
{
CloseHandle(hThrds[slot]);
hThrds[slot] = NULL;
}
}
printf("All slots terminated\n");
return EXIT_SUCCESS;
}