pthread_cond_wait pthread_cond_broadcast条件变量时要注意

#include<pthread.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>


pthread_mutex_t mymutex1 = PTHREAD_MUTEX_INITIALIZER;
 pthread_mutex_t mymutex2 = PTHREAD_MUTEX_INITIALIZER;
 pthread_cond_t  mycond  = PTHREAD_COND_INITIALIZER;
 void *mythread1(void *param)
{
pthread_mutex_lock(&mymutex1);
fprintf(stderr,"start wait this is mythread1.\n");
int nerr = pthread_cond_wait(&mycond,&mymutex1);//注意,这个会把mutex重置的
fprintf(stderr,"this is mythread1 %d.\n", nerr);
pthread_mutex_unlock(&mymutex2);//由于thread2重置了mycond变量中的mutex,所以在这地方要释放mymutex2
return NULL;
}
void *mythread2(void *param)
{
pthread_mutex_lock(&mymutex2);
fprintf(stderr,"start wait this is mythread2.\n");
int nerror = pthread_cond_wait(&mycond,&mymutex2);// 先运行thread 1,跑到这语句时,把原来的conn条件变量的mutex重置成mutex2了
fprintf(stderr,"this is mythread2. %d\n", nerror);
pthread_mutex_unlock(&mymutex2);
return NULL;
}
 int main(int argc,char* argv[],char *envp[])
{
int i;
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,mythread1,NULL);
pthread_create(&tid2,NULL,mythread2,NULL);
int ava = getchar();


pthread_mutex_lock(&mymutex1);
pthread_mutex_lock(&mymutex2);
printf("main thread. %d\n", ava);
if(pthread_cond_broadcast(&mycond)){
printf("error\n");
return 1;
}
pthread_mutex_unlock(&mymutex2);
pthread_mutex_unlock(&mymutex1);
pthread_join(tid2, NULL);
printf("this is main thread. %d\n", ava);
return 0;

}

g++ test.cpp -lpthread

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值