一步一步学Linux C:线程互斥实例


一步一步学Linux C:线程互斥实例
  1. /*编译时注意,要手动连接库*/  
  2. #include <stdio.h>     
  3. #include <pthread.h>     
  4. #include <unistd.h>     
  5. #include <stdlib.h>     
  6.    
  7. static int value = 0;    
  8. pthread_mutex_t mutex;    
  9.    
  10. void func(void* args)    
  11. {    
  12.     while(1)    
  13.     {    
  14.         pthread_mutex_lock(&mutex);    
  15.         sleep(1);    
  16.         value ++;    
  17.         printf("value = %d!\n", value);    
  18.         pthread_mutex_unlock(&mutex);    
  19.     }    
  20. }    
  21.    
  22. int main()    
  23. {    
  24.     pthread_t pid1, pid2;    
  25.     pthread_mutex_init(&mutex,NULL);      
  26.    
  27.     if(pthread_create(&pid2,NULL,&func,NULL))    
  28.     {    
  29.         return -1;    
  30.     }    
  31.    
  32.     if(pthread_create(&pid1,NULL,&func,NULL))    
  33.     {    
  34.         return -1;    
  35.     }    
  36.     while(1)    
  37.         sleep(0);    
  38.    
  39.     return 0;    
  40. }  

编译时要手动连接库:详细说明见:

相关内容