首页 > 代码库 > 生成者消费者(线程同步,互斥,条件变量)

生成者消费者(线程同步,互斥,条件变量)

#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(&notEmpty,&buf);        }        printf("consume %d\n",begin);        begin = (begin+1)%max;        cnt--;        pthread_mutex_unlock(&buf);        sleep(C_SLEEP);        pthread_cond_signal(&notFull);    }    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(&notFull,&buf);        }        printf("produce %d\n",end);        end = (end+1)%max;        cnt++;        pthread_mutex_unlock(&buf);        sleep(P_SLEEP);        pthread_cond_signal(&notEmpty);    }    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;}

 

生成者消费者(线程同步,互斥,条件变量)