当前位置:首页 > 嵌入式培训 > 嵌入式学习 > 讲师博文 > 条件变量演示

条件变量演示 时间:2017-10-25      来源:未知

/*

有两个共享变量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;

}

上一篇:Zigbee——串口无线透传分析

下一篇:Qt 5.6以上版本的MJPG-STREAMER视频播放实现

热点文章推荐
华清学员就业榜单
高薪学员经验分享
热点新闻推荐
前台专线:010-82525158 企业培训洽谈专线:010-82525379 院校合作洽谈专线:010-82525379 Copyright © 2004-2022 北京华清远见科技集团有限公司 版权所有 ,京ICP备16055225号-5京公海网安备11010802025203号

回到顶部