#include <windows.h> #include <stdlib.h> #include <stdio.h> #include <TCHAR.h>
DWORD WINAPI ThreadFun(LPVOID); #define THREAD_POOL_SIZE 5 HANDLE MySem;
int main(){ HANDLE hThrds[THREAD_POOL_SIZE]; int slot=0; DWORD threadId[THREAD_POOL_SIZE]; int i; DWORD rc; long len;
MySem = CreateSemaphore(NULL, 2, 5, _T("MySem")); for(i=0;i<THREAD_POOL_SIZE;i++){ hThrds[i]=CreateThread(NULL, 0, ThreadFun, (LPVOID)i, 0, &threadId[i]); if(hThrds[i]) { printf("Thread %d lanched \n", i); } } rc = WaitForMultipleObjects(THREAD_POOL_SIZE, hThrds, true, INFINITE); slot = rc - WAIT_OBJECT_0; if(slot>=0 && slot<THREAD_POOL_SIZE) printf("All thread terminite\n");
CloseHandle(MySem); for(i=0;i<THREAD_POOL_SIZE;i++){ CloseHandle(hThrds[i]); } return 0; }
DWORD WINAPI ThreadFun(LPVOID n){ int i; long len; WaitForSingleObject(MySem, INFINITE); for(i=0;i<5;i++){ printf("t%d do %d\n", n, i); Sleep(1000); } ReleaseSemaphore(MySem, 1, &len); printf("Thread %d terminate\n", n); return 0; }
|