互斥量和条件变量实现生产者消费者模型

来源:互联网 发布:软件天金加金 编辑:程序博客网 时间:2024/04/20 07:22
/*producer and constmer*/#include<stdio.h>#include<pthread.h>#include<string.h>#include<stdlib.h>pthread_mutex_t mutex;pthread_cond_t cond;//int good = 0;void *customer(void *argv)//消费者代码{while(1){pthread_mutex_lock(&mutex);if(good == 0){pthread_cond_wait(&cond,&mutex);//当产品为0的时候,阻塞在条件变量,并释放自己的互斥锁。解除阻塞后会去获取该互斥锁}good--;printf("customer:%d\n",good);pthread_mutex_unlock(&mutex);//消费完成释放互斥锁sleep(rand()%3);//实现随机消费}return NULL;}void *producer(void *argv){while(1){pthread_mutex_lock(&mutex);//获取互斥锁进行生产good++;printf("producer:%d\n",good);pthread_mutex_unlock(&mutex);//生产完成释放该锁if(good == 1)pthread_cond_signal(&cond);//产品==1的时候释放阻塞在产品为0的线程,通知其开始消费sleep(rand()%3);}return NULL;}void main(){pthread_t pt1,pt2;pthread_mutex_init(&mutex,NULL);//初始化互斥锁pthread_cond_init(&cond,NULL);//初始化条件变量
pthread_create(&pt1,NULL,customer,NULL);//创建消费者线程pthread_create(&pt2,NULL,producer,NULL);//创建生产者线程
pthread_join(pt1,NULL);//阻塞等待结束pthread_join(pt2,NULL);
pthread_mutex_destroy(&mutex);//销毁对应的锁pthread_cond_destroy(&cond);//销毁条件变量}

阅读全文
0 0
原创粉丝点击