这是一个使用条件变量的例子,后面的附图很清楚的说明了整个过程中互斥量的加锁和解锁的过程。
/*
*条件变量使用例程
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
static int x=0;
/*消费者线程工作函数*/
static void* thread_eat(void* arg)
{
int id=(int)arg;
printf("thread %d run\n",id);
while(1){
pthread_mutex_lock(&lock);
/*判断条件是否满足,如果 x<=0,则等待条件变量cond*/
while(x<=0){
printf("thread %d will wait on cond\n",id);
pthread_cond_wait(&cond,&lock);
printf("thread %d wakeup \n",id);
}
x--;
printf("thread %d eat one,now x=%d\n",id,x);
pthread_mutex_unlock(&lock);
sleep(1);
}
return NULL;
}
/*生产者*/
static void* thread_feed(void* arg)
{
while(1){
pthread_mutex_lock(&lock);
x+=4;
/*触发条件变量*/
pthread_cond_broadcast(&cond);
printf("thread feed set x=%d\n",x);
pthread_mutex_unlock(&lock);
sleep(2);
}
return NULL;
}
int main()
{
int i;
pthread_t tid;
for(i=0;i<3;++i){
if(pthread_create(&tid,NULL,thread_eat,(void*)i)){
perror("pthread_create");
return -1;
}
}
sleep(6); /*保证消费者先运行*/
if(pthread_create(&tid,NULL,thread_feed,NULL)){
perror("pthread_create");
return -1;
}
pthread_join(tid,NULL);
return 0;
}
![](http://hi.csdn.net/attachment/201109/2/0_1314974760AEYo.gif)