/* pthread9-2.c 条件变量(生产者与消费者的关系)*/
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int count=5;
void *decrement(void *arg)//消费
{
while(1)
{
pthread_mutex_lock(&mutex);
//printf("thread1 got lock!\n");
while(count<=0)
{
printf("count<=0,thread1 is hanging!\n");//线程1正在挂起!
pthread_cond_wait(&cond,&mutex);
sleep(1);
printf("sleep!\n");
}
count=count-1;
pthread_mutex_unlock(&mutex);
//printf("thread1 released the lock!\n");
if(count==9)
{
printf("count=9,thread1 is over!\n");
return NULL;
}
}
}
void *increment(void *arg)//生产
{
sleep(1);
while(1)
{
pthread_mutex_lock(&mutex);
//printf("thread2 got lock!\n");
count=count+1;
if(count>0)
{
printf("count=%d,change cond state!\n",count);
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
//printf("thread2 released the lock!\n");
if(count==10)
{
printf("count=10,thread2 is over!\n");
return NULL;
}
}
}
int main()
{
int i1=1,i2=1;
pthread_t id1,id2;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&id1,NULL,decrement,NULL);//消费
pthread_create(&id2,NULL,increment,NULL);//生产
i2=pthread_join(id2,NULL);
i1=pthread_join(id1,NULL);
if((i2==0)&&(i1==0))
{
printf("count=%d,the main thread!\n",count);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
return 0;
}
}