条件变量实现生产者消费者问题
生产者消费者是典型的线程同步问题,生产者往共享区域中生产加入产品,消费者往共享区域中消费取出产品。
生产者:若共享区域未满,则加入产品,并通知消费者;若共享区域已满,则等待消费者消费。
消费者:若共享区域为空,则等待生产者生产;若共享区域未满,则消费并通知生产者。
#include#include #include #include 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(¬full, &mutex); } new->next = head; head = new; task_num++; printf("producer:%d\n", new->data); pthread_mutex_unlock(&mutex); pthread_cond_signal(¬empty); sleep(1); } } void* consumer(void* arg){ while(1){ pthread_mutex_lock(&mutex); while(head==NULL){ //while循环防止wait返回时发生虚假唤醒 pthread_cond_wait(¬empty, &mutex); } task *old = head; head = head->next; task_num--; printf("consumer:%d\n", old->data); pthread_mutex_unlock(&mutex); pthread_cond_signal(¬full); 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(¬empty); pthread_cond_destroy(¬full); return 0; }