/*
有兩個共享變量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;
}