线程同步-生产者消费者条件变量模型

线程同步典型案例为生产者消费者模型,而借助条件变量来实现这一模型,时比较常见的一种做法。假定有2个线程,一个模拟生产者行为,一个模拟消费者行为。两个线程同时操作一个共享资源(一般称之为汇聚),生产者向其中添加产品,消费者从中消费掉产品;
看如下实例,使用条件变量模拟生产者,消费者问题:

 #include <stdio.h>
  2 #include <string.h>
  3 #include <pthread.h>
  4 #include <unistd.h>
  5 #include <stdlib.h>
  6 
  7 struct msg
  8 {
  9         int num;
 10         struct msg* next;
 11 };
 12 
 13 struct msg* head = NULL;
 14 struct msg* mp = NULL;
 15 
 16 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//初始化一把互斥锁
 17 
 18 pthread_cond_t hasproduct = PTHREAD_COND_INITIALIZER;//初始化一个条件变量
 19 
 20 void* producter(void* arg)
 21 {
 22         while(1)
 23         {
 24                 mp = (struct msg*) malloc(sizeof(struct msg));//创建一个msg节点
 25                 mp->num = rand() % 400 + 1;
 26                 printf("-----------------producter %d \n",mp->num);
 27                 //把产品放到公共区域,但是产品在公共区,需要加锁才能放进去
 28                 pthread_mutex_lock(&mutex);
 29                 mp->next = head;//因为head是头节点,刚开始是空的,
 30                 head= mp;
 31                 printf("head->num = %d\n",head->num);
 32                 pthread_mutex_unlock(&mutex);
 33 
 34                 pthread_cond_signal(&hasproduct);//将等待在该条件变量上的线程唤醒,唤醒等待的线程,就是使用pthread_cond_wait的线程;
 35                 sleep(rand() % 5);
 36         }
 37         return NULL;
 38 }void* consumer(void* arg)
 41 {
 42         for(;;)//为了解决如果具有多个消费者线程的问题,不能用if替换
 43         {
 44                 pthread_mutex_lock(&mutex);
 45                 while(head == NULL)//头指针为空,说明没有产品
 46                 {
 47                         pthread_cond_wait(&hasproduct,&mutex);
 48                 }
 49                 mp = head;
 50                 head = mp -> next;//消费掉一个产品;
 51                 pthread_mutex_unlock(&mutex);
 52                 printf("--------------------------consumer %d\n",mp->num);
 53                 free(mp);
 54                 sleep(rand() % 5);
 55         }
 56         return NULL;
 57 }
 58 int main()
 59 {
 60         srand(time(NULL));
 61         pthread_t ptid,ctid;
 62         pthread_create(&ptid,NULL,producter,NULL);
 63         pthread_create(&ctid,NULL,consumer,NULL);
 64 
 65 
 66         pthread_join(ptid,NULL);
 67         pthread_join(ctid,NULL);
 68         return 0;S
 69 }

	

猜你喜欢

转载自blog.csdn.net/weixin_37603532/article/details/89484081