Semaphore多线程实例
1 // SemaphoreMultiThread.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <stdio.h> 6 #include "windows.h" 7 #define MAX_SEM_COUNT 6 8 #define THREADCOUNT 12 9 10 11 HANDLE ghSemaphore; 12 DWORD WINAPI ThreadProc(LPVOID lparam); 13 14 int _tmain(int argc, _TCHAR* argv[]) 15 { 16 HANDLE aThread[THREADCOUNT]; 17 DWORD ThreadID; 18 int i; 19 20 //Create a semaphore with initial and max counts of MAX_SEM_COUNT 21 ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL); 22 if (ghSemaphore == NULL) 23 { 24 printf("CreateSemphore error"); 25 return 1; 26 } 27 for (int i=0; i<THREADCOUNT; i++) 28 { 29 aThread[i] = CreateThread(NULL, 30 0, 31 (LPTHREAD_START_ROUTINE)ThreadProc, 32 NULL, 33 0, 34 &ThreadID); 35 if (aThread[i] == NULL) 36 { 37 printf("Create Thread failed\n"); 38 return 1; 39 } 40 } 41 WaitForMultipleObjects(THREADCOUNT,aThread,TRUE,INFINITE); 42 //Close thread and semphore 43 for (int i=0; i<THREADCOUNT; i++) 44 { 45 CloseHandle(aThread[i]); 46 } 47 CloseHandle(ghSemaphore); 48 system("pause"); 49 return 0; 50 } 51 DWORD WINAPI ThreadProc(LPVOID lparam) 52 { 53 DWORD dwWaitResult; 54 BOOL bContinue = TRUE; 55 while (bContinue) 56 { 57 dwWaitResult = WaitForSingleObject(ghSemaphore,3L); 58 switch (dwWaitResult) 59 { 60 //Try to enter the semaphore gate. 61 case WAIT_OBJECT_0: 62 printf("Thread %d wait successed \n",GetCurrentThreadId()); 63 bContinue = FALSE; 64 Sleep(5); 65 for (int x = 0; x<10; x++) 66 { 67 printf("Thread %d task!\n",GetCurrentThreadId()); 68 } 69 if (!ReleaseSemaphore(ghSemaphore, 1, NULL)) 70 { 71 printf("ReleaseSemaphore error:%d\n",GetLastError()); 72 } 73 break; 74 case WAIT_TIMEOUT: 75 printf("Thread %d: wait timeout",GetCurrentThreadId()); 76 break; 77 } 78 79 } 80 return TRUE; 81 }
作者:imFolish
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。