c 生产者与消费者

pthread_cond_timedwait 函数还有一个额外的参数可以设定等待超时,如果到达了abstime 所指
定的时刻仍然没有别的线程来唤醒当前线程,就返回ETIMEDOUT 。一个线程可以调
用pthread_cond_signal 唤醒在某个Condition Variable上等待的另一个线程,也可以调
用pthread_cond_broadcast唤醒在这个Condition Variable上等待的所有线程。
下面的程序演示了一个生产者-消费者的例子,生产者生产一个结构体串在链表的表头上,消费
者从表头取走结构体。

#include<stdio.h>
  2 #include<stdlib.h>
  3 #include<pthread.h>
  4 #include<math.h>
  5 struct student{
  6     struct student *next;
  7     int data;
  8 };
  9 struct student *head;
 10 pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
 11 pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
 12 void *consumer(void *p){
 13     struct student *st;
 14     for(;;){
 15         pthread_mutex_lock(&lock);
 16         while(head==NULL){
 17             pthread_cond_wait(&cond,&lock);
 18         }
 19         st=head;
 20         head=st->next;
 21         pthread_mutex_unlock(&lock);
 22         printf("consume %d\n",st->data);
 23         free(st);
 24         sleep(1);
 25     }
 26 
 27 }
 28 void *producer(void *p){
 29     struct student *st;
 30     for(;;){
 31         st=malloc(sizeof(struct student));
 32         st->data=rand()%1000+1;
 33 
 34         printf("producer %d\n",st->data);
 35         pthread_mutex_lock(&lock);
 36         st->next=head;
 37         head=st;
 38         pthread_mutex_unlock(&lock);
 39         pthread_cond_signal(&cond);
 40         sleep(1);
    }
 43 }
 44 
 45 int main(){
 46     pthread_t p1;
 47     pthread_t p2;
 48     pthread_create(&p1,NULL,producer,NULL);
 49     pthread_create(&p2,NULL,consumer,NULL);
 50     pthread_join(p1,NULL);
 51     pthread_join(p2,NULL);
 52 
 53 }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值