条件变量是为了控制多线程的互斥问题,同时个人觉得有点多线程协作同步的意思在里面。消费者线程等待取生产者线程提供的资源,生产者线程生产产品后就通知唤醒消费者线程进行资源获取。一般条件变量与互斥量共用。
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> #include <string.h> typedef struct product_node { char name[32]; int number; struct product_node *next; }product; product *product_container = NULL; int counter = 0; pthread_cond_t product_cond; pthread_mutex_t product_mutex; void * producer(void *arg) { while(1) { time_t tt = time(NULL); product *tmp = (product *)malloc(sizeof(product)); if (tmp == NULL) { printf("malloc error\n"); pthread_exit((void *)-1); } ctime_r(&tt, tmp->name); pthread_mutex_lock(&product_mutex); tmp->number = counter++; tmp->next = product_container; product_container = tmp; pthread_mutex_unlock(&product_mutex); pthread_cond_broadcast(&product_cond); //如果不加sleep, 那么生产者线程会在消费者线程sleep途中一直能得到锁 //导致counter++无数次 sleep(1); } } void * consumer(void *arg) { product *one_product; while(1) { pthread_mutex_lock(&product_mutex); while(product_container == NULL) { //阻塞线程同时释放互斥锁,这就是为什么需要传递一个互斥锁的原因,如果第二个参数的互斥锁和上面lock //时候的锁不一致就会导致问题。释放互斥锁的原因是让生产者线程能够及时地获取锁放入产品。当条件变量 //得到满足同时能够离开循环, 刚才释放的互斥锁又会重新加上 pthread_cond_wait(&product_cond, &product_mutex); } one_product = product_container; product_container = product_container->next; pthread_mutex_unlock(&product_mutex); one_product->name[strlen(one_product->name) - 1] = 0; printf("name[%s] get number[%d] product\n", one_product->name, one_product->number); free(one_product); sleep(1); } } int main() { pthread_t worker, saler; pthread_cond_init(&product_cond, NULL); pthread_mutex_init(&product_mutex, NULL); pthread_create(&worker, NULL, producer, NULL); pthread_create(&saler, NULL, consumer, NULL); pthread_join(worker, NULL); pthread_join(saler, NULL); pthread_cond_destroy(&product_cond); pthread_mutex_destroy(&product_mutex); return 0; }