讲师博文
条件变量演示 来源 : 未知     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视频播放实现

400-611-6270

Copyright © 2004-2024 华清远见教育科技集团 版权所有
京ICP备16055225号-5京公海网安备11010802025203号