- #include <windows.h>
- #include <stdio.h>
- #define NUMTHREADS 4
- HANDLE hSemaphore;
- void UseSemaphore(void);
- DWORD WINAPI SemaphoreThread(LPVOID lpParam);
- int main(void){
- UseSemaphore();
- }
- void UseSemaphore(void){
- HANDLE hThread[NUMTHREADS];
- INT i;
- LONG lMax;
- CHAR cMax;
- printf("将创建%d个线程,获得信号量的线程可以向屏幕打印.\n请输入信号量的最大计数1-%d:",NUMTHREADS,NUMTHREADS);
- cMax = getch();
- printf("%c\n",cMax);
- lMax = cMax & 0xF;
- if(lMax<0 || lMax>NUMTHREADS){
- printf("请输入1-%d.\n",NUMTHREADS);
- }
- hSemaphore = CreateSemaphore(NULL,lMax,lMax,NULL);
- if(hSemaphore == NULL){
- printf("Create Semaphorec error.(%d)\n",GetLastError());
- }
- for(i=0;i<NUMTHREADS;i++){
- hThread[i] = CreateThread(NULL,0,SemaphoreThread,&i,0,NULL);
- if(hThread[i] == NULL){
- printf("Create Threads error.(%d)\n",GetLastError());
- return;
- }
- }
- WaitForMultipleObjects(NUMTHREADS,hThread,TRUE,INFINITE);
- }
- DWORD WINAPI SemaphoreThread(LPVOID lpParam){
- DWORD dwWaitResult;
- BYTE lpRead[16];
- DWORD j = 0;
- DWORD dwPreviousCount;
- for(;j<3;j++){
- Sleep(rand()%1000);
- dwWaitResult = WaitForSingleObject(hSemaphore,INFINITE);
- switch(dwWaitResult){
- case WAIT_OBJECT_0:
- printf("\nProcess %d Gets Semaphore",GetCurrentThreadId());
- break;
- default:
- printf("\nprocess %u wait error:%u",GetCurrentThreadId(),GetLastError());
- }
- Sleep(rand()%1000);
- if(!ReleaseSemaphore(hSemaphore,1,&dwPreviousCount))
- {
- printf("\nprocess %u Release Semaphore error:%d",GetCurrentProcessId(),GetLastError());
- }else
- {
- printf("\nProcess %u Release Semaphore,previous count is %u",GetCurrentProcessId(),dwPreviousCount);
- }
- }
- return 1;
- }
本文转hackfreer51CTO博客,原文链接:http://blog.51cto.com/pnig0s1992/673401,如需转载请自行联系原作者