Chinaunix

标题: pthread_cond_wait并未等待signal调用就返回了,为何? [打印本页]

作者: cdsfiui    时间: 2017-06-25 12:53
标题: pthread_cond_wait并未等待signal调用就返回了,为何?
本帖最后由 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..."这句话。
这是为什么呢,哪个地方理解或者程序有错误? 还请帮忙纠正。
谢谢。







欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2