首页 > 代码库 > 生成者消费者(线程同步,互斥,条件变量)
生成者消费者(线程同步,互斥,条件变量)
#include <unistd.h>#include "stdio.h"#include <stdlib.h>#include <pthread.h>#define N_CONSUMER 3 //消费者数量#define N_PRODUCER 2 //生产者数量#define C_SLEEP 1 //控制 consumer 消费的节奏#define P_SLEEP 1 //控制 producer 生产的节奏pthread_t ctid[N_CONSUMER];//consumer thread idpthread_t ptid[N_PRODUCER];//producer thread idpthread_cond_t notFull,notEmpty;//缓冲区不满;缓冲区不空pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;//用于锁住缓冲区//从 begin 到 end(不含end) 代表产品//cnt 代表产品数量//max 代表库房的容量,即最多生产多少产品int begin = 0,end = 0, cnt = 0, max = 4;void * consumer(void * pidx)//consumer thread idx{ printf("consumer thread id %d\n",*((int *)pidx)); while(1) { pthread_mutex_lock(&buf); while(cnt == 0){//当缓冲区空时 pthread_cond_wait(¬Empty,&buf); } printf("consume %d\n",begin); begin = (begin+1)%max; cnt--; pthread_mutex_unlock(&buf); sleep(C_SLEEP); pthread_cond_signal(¬Full); } pthread_exit((void *)0);}void * producer(void * pidx)//producer thread idx{ printf("producer thread id %d\n",*((int *)pidx)); while(1) { pthread_mutex_lock(&buf); while(cnt == max){//当缓冲区满时 pthread_cond_wait(¬Full,&buf); } printf("produce %d\n",end); end = (end+1)%max; cnt++; pthread_mutex_unlock(&buf); sleep(P_SLEEP); pthread_cond_signal(¬Empty); } pthread_exit((void *)0);}int main(){ int i = 0; for(i = 0; i < N_CONSUMER; i++) { ;int * j = (int *) malloc(sizeof(int)); *j = i; if(pthread_create(&ctid[i],NULL,consumer,j) != 0) { perror("create consumer failed\n"); exit(1); } } for(i = 0; i < N_PRODUCER; i++) { int * j = (int *) malloc(sizeof(int)); *j = i; if(pthread_create(&ptid[i],NULL,producer,j) != 0) { perror("create producer failed\n"); exit(1); } } while(1) { sleep(10); } return 0;}
生成者消费者(线程同步,互斥,条件变量)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。