且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用互斥对象进行线程同步

更新时间:2022-09-19 13:55:47

 


  1. #include <windows.h> 
  2. #include <stdio.h> 
  3.  
  4. #define NUM_THREADS 4 
  5.  
  6. DWORD dwCounter = 0; 
  7. HANDLE hMutex; 
  8.  
  9. void UseMutex(void); 
  10. DWORD WINAPI MutexThread(LPVOID lpParam); 
  11.  
  12. int main(void){ 
  13.     UseMutex(); 
  14.  
  15. void UseMutex(void){ 
  16.     INT i; 
  17.     HANDLE hThread; 
  18.     hMutex = CreateMutex(NULL,FALSE,NULL); 
  19.     if(hMutex == NULL){ 
  20.         printf("Create mutex error.(%d)\n",GetLastError()); 
  21.         return
  22.     } 
  23.     for(i=0;i<NUM_THREADS;i++){ 
  24.         hThread = CreateThread(NULL,0,MutexThread,NULL,0,NULL); 
  25.         if(hThread == NULL){ 
  26.             printf("Create thread error.(%d)\n",GetLastError()); 
  27.             return
  28.         } 
  29.     } 
  30.     Sleep(1000); 
  31.  
  32. DWORD WINAPI MutexThread(LPVOID lpParam){ 
  33.     DWORD dwMutexResult; 
  34.     dwMutexResult = WaitForSingleObject(hMutex,INFINITE); 
  35.     switch(dwMutexResult){ 
  36.     case WAIT_OBJECT_0: 
  37.         Sleep(rand()%100); 
  38.         printf("counter:%d\n",dwCounter); 
  39.         dwCounter++; 
  40.         if(!ReleaseMutex(hMutex)){ 
  41.             printf("Release Mutex error.(%d)\n",GetLastError()); 
  42.         } 
  43.         break
  44.     default
  45.         printf("Wait error.(%d)\n",GetLastError()); 
  46.         ExitProcess(0); 
  47.     } 
  48.     return 1; 

 












本文转hackfreer51CTO博客,原文链接:http://blog.51cto.com/pnig0s1992/672635,如需转载请自行联系原作者