Semaphore小测试程序
通过等待函数和ReleaseSemaphore可以确保同一时刻有有限个线程访问指定的资源。
以下是一个测试小程序
1 #include "stdafx.h" 2 #include <windows.h> 3 #include <stdio.h> 4 5 HANDLE hSemaphore; 6 7 typedef struct _ThreadParam{ 8 char name[100]; 9 }ThreadParam; 10 11 DWORD WINAPI ThreadProc(LPVOID lpParam) 12 { 13 ThreadParam *pTp = (ThreadParam*)lpParam; 14 15 printf("thread %s waiting...\n", pTp->name); 16 WaitForSingleObject(hSemaphore, INFINITE); 17 printf("thread %s entering thread..\n", pTp->name); 18 19 for (volatile int i = 0; i < 65535; i++) 20 { 21 for (volatile int j = 0; j < 100; j++) 22 { 23 int k = i * j; 24 } 25 } 26 27 printf("thread %s leaving thread..\n", pTp->name); 28 ReleaseSemaphore(hSemaphore, 1, NULL); 29 return 0; 30 } 31 32 int main(int argc, char* argv[]) 33 { 34 const int threadCount = 10; 35 HANDLE hThread[threadCount]; 36 DWORD dwTemp; 37 ThreadParam *tp[threadCount]; 38 39 hSemaphore = CreateSemaphore(NULL, 2, 2, NULL); 40 41 for (int i = 0; i < threadCount; i++) 42 { 43 tp[i] = new ThreadParam; 44 wsprintf(tp[i]->name, "%d", i); 45 hThread[i] = CreateThread(NULL, 0, ThreadProc, tp[i], NULL, &dwTemp); 46 } 47 48 WaitForMultipleObjects(10, hThread, TRUE, INFINITE); 49 50 for (int i = 0; i < threadCount; i++) 51 { 52 delete tp[i]; 53 } 54 return 0; 55 }