1. 初始化:
条件变量采用的数据类型是pthread_cond_t, 在使用之前必须要进行初始化, 这包括两种方式:
- 静态: 可以把常量PTHREAD_COND_INITIALIZER给静态分配的条件变量.
- 动态: pthread_cond_init函数, 是释放动态条件变量的内存空间之前, 要用pthread_cond_destroy对其进行清理.
int pthread_cond_init(pthread_cond_t *restrict cond, pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//条件变量生产者和消费者
pthread_cond_t condc,condp;
pthread_mutex_t the_mutex;
unsigned int buffer = 0;//全局共享资源
const int MAX = 100;
void *producer(void *ptr){
for(int i = 1; i < MAX; i++){
pthread_mutex_lock(&the_mutex);
//producer在当buffer内容生产中便进入等待
while(buffer != 0) pthread_cond_wait(&condp, &the_mutex);
sleep(1);
buffer = i;
printf("producer pthread produce one production %d.\n", i);
//生产者线程生产完成
pthread_cond_broadcast(&condc);//唤醒两个消费者线程
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer1(void *ptr){
for(int i = 1; i < MAX; i++){
pthread_mutex_lock(&the_mutex);
while(buffer == 0)//生产者生产的产品消费完,消费者线程阻塞
pthread_cond_wait(&condc, &the_mutex);
printf("consumer1 pthread consume one production %d.\n", buffer);
buffer = 0;
pthread_cond_signal(&condp);//并且发送信号给生产者线程
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer2(void *ptr){
for(int i = 1; i < MAX; i++){
pthread_mutex_lock(&the_mutex);
while(buffer == 0) pthread_cond_wait(&condc, &the_mutex);
printf("consumer2 pthread consume one production %d.\n", buffer);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(void){
pthread_t pro, con1, con2;
pthread_mutex_init(&the_mutex,0);
pthread_cond_init(&condc,0);//动态初始化条件变量
pthread_cond_init(&condp,0);
pthread_create(&con1, 0, consumer1, 0);
pthread_create(&pro, 0, producer, 0);
pthread_create(&con2, 0, consumer2, 0);
pthread_join(pro, 0);
pthread_join(con1, 0);
pthread_join(con2, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}