打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Linux互斥锁的使用代码实现


  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. }  

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


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





本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Linux性能评测工具之一:gprof篇
Linux多线程编程小结
编程实现生产者消费者问题
200行C代码实现简单线程池 - Linux内核编程 - 举世无双的学习之路
Linux 线程池
linux下C实现多线程
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服