免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1828 | 回复: 0
打印 上一主题 下一主题

[Linux] pthread_cond_wait并未等待signal调用就返回了,为何? [复制链接]

论坛徽章:
2
2015年迎新春徽章
日期:2015-03-04 10:16:532015元宵节徽章
日期:2015-03-06 15:53:22
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2017-06-25 12:53 |只看该作者 |倒序浏览
本帖最后由 cdsfiui 于 2017-06-25 12:56 编辑

我设计了一个小的程序做实验:

1. 主线程创建一个子线程,子线程调用pthread_cond_wait等待信号
2. 主线程睡眠3秒钟,发出signal
3. 子线程响应信号,打印一句话.

程序如下:

  1. #include<pthread.h>
  2. #include<unistd.h>
  3. #include<cassert>
  4. #include<iostream>
  5. using namespace std;
  6. pthread_mutex_t mt;
  7. pthread_cond_t cond;
  8. pthread_t tid;
  9. void* tf(void*arg){
  10.     pthread_mutex_lock(&mt);
  11.     pthread_cond_wait(&cond, &mt);
  12.     cout<<"After main thread sleeps 3 seconds\n";
  13.     return NULL;
  14. }
  15. int main(){
  16.     assert(0==pthread_mutex_init(&mt,NULL));
  17.     pthread_create(&tid,NULL,tf,NULL);
  18.     sleep(3);
  19.     pthread_cond_signal(&cond);
  20.     pthread_join(tid,NULL);//Is 2nd parameter useful?
  21.     pthread_cond_destroy(&cond);
  22.     return 0;
  23. }

复制代码

但是实际上,程序的输出是子线程立刻打印了"After main..."这句话。
这是为什么呢,哪个地方理解或者程序有错误? 还请帮忙纠正。
谢谢。


您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP