c 生产者与消费者

来源:互联网 发布:江北新区 知乎 编辑:程序博客网 时间:2024/04/27 04:51
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 }