条件变量实现生产者消费者问题

生产者消费者是典型的线程同步问题,生产者往共享区域中生产加入产品,消费者往共享区域中消费取出产品。

生产者:若共享区域未满,则加入产品,并通知消费者;若共享区域已满,则等待消费者消费。

消费者:若共享区域为空,则等待生产者生产;若共享区域未满,则消费并通知生产者。

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>

const int TASK_SIZE = 100;

typedef struct Task{
    int data;
    struct Task *next;
}task;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;  //共享区域互斥锁
pthread_cond_t notempty = PTHREAD_COND_INITIALIZER;  //任务非空条件变量
pthread_cond_t notfull = PTHREAD_COND_INITIALIZER;  //任务满条件变量

 task *head = NULL;
 int task_num = 0;

 void *producer(void *arg)
 {

     while (1)
     {
        task *new = malloc(sizeof(task));
        new->data = rand() % 100;

        pthread_mutex_lock(&mutex);
        while(task_num == TASK_SIZE){
            pthread_cond_wait(&notfull, &mutex);
        }
        new->next = head;
        head = new;
        task_num++;
        printf("producer:%d\n", new->data);
        pthread_mutex_unlock(&mutex);

        pthread_cond_signal(&notempty);

        sleep(1);
     }
}


void* consumer(void* arg){
    while(1){
        pthread_mutex_lock(&mutex);
        while(head==NULL){  //while循环防止wait返回时发生虚假唤醒
            pthread_cond_wait(&notempty, &mutex);
        }
        task *old = head;
        head = head->next;
        task_num--;
        printf("consumer:%d\n", old->data);
        pthread_mutex_unlock(&mutex);

        pthread_cond_signal(&notfull);

        free(old);

        sleep(2);
    }

}


int main(){

    pthread_t pt, ct;
    
    pthread_mutex_init(&mutex, NULL);

    pthread_create(&pt, NULL, producer, NULL);
    pthread_create(&ct, NULL, consumer, NULL);

    pthread_join(pt, NULL);
    pthread_join(ct, NULL);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&notempty);
    pthread_cond_destroy(&notfull);

    return 0;
}

  

posted @ 2022-04-16 21:34  Kayden_Cheung  阅读(121)  评论(0编辑  收藏  举报
//目录