1. #include <windows.h> 
  2. #include <stdio.h> 
  3.  
  4. #define NUMTHREADS 4 
  5.  
  6. HANDLE hSemaphore; 
  7.  
  8. void UseSemaphore(void); 
  9. DWORD WINAPI SemaphoreThread(LPVOID lpParam); 
  10.  
  11. int main(void){ 
  12.     UseSemaphore(); 
  13.  
  14. void UseSemaphore(void){ 
  15.     HANDLE hThread[NUMTHREADS]; 
  16.     INT i; 
  17.     LONG lMax; 
  18.     CHAR cMax; 
  19.     printf("将创建%d个线程,获得信号量的线程可以向屏幕打印.\n请输入信号量的最大计数1-%d:",NUMTHREADS,NUMTHREADS); 
  20.     cMax = getch(); 
  21.     printf("%c\n",cMax); 
  22.     lMax = cMax & 0xF; 
  23.     if(lMax<0 || lMax>NUMTHREADS){ 
  24.         printf("请输入1-%d.\n",NUMTHREADS); 
  25.     } 
  26.     hSemaphore = CreateSemaphore(NULL,lMax,lMax,NULL); 
  27.     if(hSemaphore == NULL){ 
  28.         printf("Create Semaphorec error.(%d)\n",GetLastError()); 
  29.     } 
  30.     for(i=0;i<NUMTHREADS;i++){ 
  31.         hThread[i] = CreateThread(NULL,0,SemaphoreThread,&i,0,NULL); 
  32.         if(hThread[i] == NULL){ 
  33.             printf("Create Threads error.(%d)\n",GetLastError()); 
  34.             return
  35.         } 
  36.     } 
  37.     WaitForMultipleObjects(NUMTHREADS,hThread,TRUE,INFINITE); 
  38.  
  39. DWORD WINAPI SemaphoreThread(LPVOID lpParam){ 
  40.     DWORD dwWaitResult; 
  41.     BYTE lpRead[16]; 
  42.     DWORD j = 0; 
  43.     DWORD dwPreviousCount; 
  44.  
  45.     for(;j<3;j++){ 
  46.         Sleep(rand()%1000); 
  47.         dwWaitResult = WaitForSingleObject(hSemaphore,INFINITE); 
  48.         switch(dwWaitResult){ 
  49.         case WAIT_OBJECT_0: 
  50.             printf("\nProcess %d Gets Semaphore",GetCurrentThreadId()); 
  51.             break
  52.         default
  53.             printf("\nprocess %u wait error:%u",GetCurrentThreadId(),GetLastError()); 
  54.         } 
  55.         Sleep(rand()%1000); 
  56.         if(!ReleaseSemaphore(hSemaphore,1,&dwPreviousCount)) 
  57.         { 
  58.             printf("\nprocess %u Release Semaphore error:%d",GetCurrentProcessId(),GetLastError()); 
  59.         }else 
  60.         { 
  61.             printf("\nProcess %u Release Semaphore,previous count is %u",GetCurrentProcessId(),dwPreviousCount); 
  62.         } 
  63.     } 
  64.     return 1;