Linux互斥锁的使用代码实现

来源:互联网 发布:手机qq软件 编辑:程序博客网 时间:2024/05/11 00:30

From: http://blog.csdn.net/leo115/article/details/8037869

[cpp] view plaincopy
  1. #include <stdio.h>  
  2. #include <pthread.h>  
  3. #include <sched.h>  
  4. #include <unistd.h>  
  5.   
  6. //对临界区的保护问题  
  7.   
  8. void *fun1(void *arg);  
  9. void *fun2(void *arg);  
  10.   
  11. int buffer = 0;  
  12. pthread_mutex_t mutex;  
  13. int running = 1;  
  14.   
  15. int main(void )  
  16. {  
  17.     pthread_t pt1;  
  18.     pthread_t pt2;  
  19.   
  20.     pthread_mutex_init(&mutex,NULL);  
  21.   
  22.     pthread_create(&pt1,NULL,fun1,(void*)&running);  
  23.     pthread_create(&pt2,NULL,fun2,(void*)&running);  
  24.   
  25.     usleep(1000);  
  26.     running=0;  
  27.     pthread_join(pt1,NULL);  
  28.     pthread_join(pt2,NULL);  
  29.     pthread_mutex_destroy(&mutex);  
  30.     return 0;  
  31. }  
  32.   
  33. void *fun1(void *arg)  
  34. {  
  35.     while(*(int *)arg)  
  36.     {  
  37.         //pthread_mutex_lock(&mutex);  
  38.     pthread_mutex_lock(&mutex);  
  39.         printf("in fun1 before add , buffer is : %d\n",buffer);  
  40.         usleep(2);  
  41.         buffer++;  
  42.         printf("in fun1 after sleep and add one ,now buffer is %d \n",buffer);  
  43.         //pthread_mutex_unlock(&mutex);  
  44.     pthread_mutex_unlock(&mutex);  
  45.         usleep(2);  
  46.     }  
  47. }  
  48.   
  49. void *fun2(void *arg)  
  50. {  
  51.     while(*(int *)arg)  
  52.     {  
  53.         //pthread_mutex_lock(&mutex);  
  54.     pthread_mutex_lock(&mutex);  
  55.         printf("in fun2 before add , buffer is : %d\n",buffer);  
  56.         usleep(2);  
  57.         buffer++;  
  58.         printf("in fun2 after sleep and add one ,now buffer is %d \n",buffer);  
  59.         //pthread_mutex_unlock(&mutex);  
  60.     pthread_mutex_unlock(&mutex);  
  61.         usleep(2);  
  62.     }  
  63.   
  64. }  

注释互斥锁前的运行结果:


注释互斥锁后的运行结果:




原创粉丝点击