linux系统编程 条件变量与互斥锁的使用

 32 #include<stdio.h>
 33 #include<pthread.h>
 34 #include<unistd.h>
 35 #include<stdlib.h>
 36 #include<string.h>
 37 pthread_mutex_t mutex;
 38 pthread_cond_t condt;
 39 pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
 40 pthread_cond_t condt=PTHREAD_COND_INITIALIZER;
 41 typedef struct food1 {
 42         struct food1 *next;
 43         int food_num;
 44 }food;
 45 food *head=NULL;
 46 food *hanburge=NULL;
 47 int num=500;
 48 void *product(void *arg)
 49 {
 50         while(1){
 51         pthread_mutex_lock(&mutex);
 52         hanburge=malloc(sizeof(food));
 53         hanburge->next=head;
 54         hanburge->food_num=num++;
 55         printf("have product:%d\n",hanburge->food_num);
 56         head=hanburge;
 57         pthread_mutex_unlock(&mutex);
 58         pthread_cond_signal(&condt);//发送条件变量给等待的线程
 59         sleep(rand()%3);
 60         }
 61 }
 62 
 63 void *commuse(void *arg)
 64 {
 65         while(1){
 66         pthread_mutex_lock(&mutex);
 67         while(head==NULL){
 68                 pthread_cond_wait(&condt,&mutex);//解开互斥锁,等待条件变量到来
 69         }
 70         printf("commuse get foodnum:%d\n",head->food_num);
 71         hanburge=head;
 72         head=head->next;
 73         free(hanburge);
 74         pthread_mutex_unlock(&mutex);
 75         sleep(rand()%3);
 76         }
 77 }
 78 
 79 void main(void)
 80 {
 81         pthread_t pthpid,compid1;
 82         pthread_create(&pthpid,NULL,product,NULL);
 83 
 84         pthread_create(&compid1,NULL,commuse,NULL);
 85 
 86         while(1);
 87 
 88 }

条件变量的优点:相较于单独使用互斥锁,条件变量可以减少竞争,限制某一方对全局变量的使用。而另一方可以随行所欲的对全局变量进行操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值