#include <windows.h> #include <process.h> #include <stdlib.h> #include <stdio.h> #include <TCHAR.h>
unsigned int WINAPI ThreadFun(LPVOID); #define THREAD_POOL_SIZE 5 HANDLE MySem;
int main(){ HANDLE hThrds[THREAD_POOL_SIZE]; int slot=0; unsigned int threadId[THREAD_POOL_SIZE]; unsigned int i; DWORD rc; long len;
MySem = CreateSemaphore(NULL, 2, 5, _T("MySem")); for(i=0;i<THREAD_POOL_SIZE;i++){ hThrds[i]=(HANDLE)_beginthreadex(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; }
unsigned int WINAPI ThreadFun(LPVOID no){ int i; long len;
WaitForSingleObject(MySem, INFINITE); for(i=0;i<5;i++){ printf("t%d do %d\n", no, i); Sleep(1000); } ReleaseSemaphore(MySem, 1, &len); printf("Thread %d terminate\n", no); return 0; }
|