条件变量演示

/*

有两个共享变量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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值