条件变量示例
条件变量最常用的场景是生产者和消费者模型
常见问题1:为什么条件变量要传入互斥锁
因为pthread_cond_wait里的操作会产生冲突(具体也不明白),调用前需要加锁,调用的过程中锁会释放,调用结束或又会上锁。总之锁传进去是会被操作的,先释放,被pthread_cond_signal激活后,又会上锁。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
struct Node{
int value;
Node *next;
Node(int val) {
value = val;
next = NULL;
}
};
Node *head;
static void * producer(void *) {
static int cnt = 0;
while(1) {
Node *tmp = new Node(cnt++);
printf("producer lock\n");
pthread_mutex_lock(&mutex);
printf("producer produce food :%d\n", tmp->value);
tmp->next = head;
head = tmp;
printf("producer unlock\n");
pthread_mutex_unlock(&mutex);
printf("buy buy buy!!!\n");
pthread_cond_signal(&cond);
sleep(1);
}
}
static void * comsumer(void *) {
while(1) {
printf("comsumer lock\n");
pthread_mutex_lock(&mutex);
while(head == NULL) {
printf("comsumer wait...\n");
pthread_cond_wait(&cond, &mutex);
}
printf("comsumer start eating\n");
Node *tmp = head;
printf("comsumer eating %d\n", head->value);
head = head->next;
printf("comsumer unlock\n");
pthread_mutex_unlock(&mutex);
delete tmp;
}
return NULL;
}
int main(int argc, char ** argv) {
pthread_t producedThread, comsumerThread;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_create(&producedThread, NULL, producer, NULL);
pthread_create(&comsumerThread, NULL, comsumer, NULL);
pthread_join(producedThread, NULL);
pthread_join(comsumerThread, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
|