/*
有两个共享变量x和y,通过互斥量mut保护,当x>y时,条件变量cond被触发
*/
#include <stdio.h>
#include <pthread.h>
int x = 0,y = 10;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *fun1(void* arg)
{
pthread_mutex_lock(&mut);
//此线程因等待条件满足而阻塞
while(x <= y)
pthread_cond_wait(&cond,&mut);
//对x,y进行操作
printf("x = %d\n",x);
printf("y = %d\n",y);
pthread_mutex_unlock(&mut);
}
void *fun2(void* arg)
{
int i;
for(i = 0; i < 20; i++)
{
pthread_mutex_lock(&mut);
//修改x,y
x = i;
printf("i = %d\n",i);
//条件满足时,唤醒阻塞的线程
if(x > y)
// pthread_cond_broadcast(&cond);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
sleep(1);
}
}
int main(void)
{
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,fun1,NULL);
pthread_create(&tid2,NULL,fun2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid1,NULL);
return 0;
}