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. 子线程响应信号,打印一句话.
程序如下:
#include<pthread.h>
#include<unistd.h>
#include<cassert>
#include<iostream>
using namespace std;
pthread_mutex_t mt;
pthread_cond_t cond;
pthread_t tid;
void* tf(void*arg){
pthread_mutex_lock(&mt);
pthread_cond_wait(&cond, &mt);
cout<<"After main thread sleeps 3 seconds\n";
return NULL;
}
int main(){
assert(0==pthread_mutex_init(&mt,NULL));
pthread_create(&tid,NULL,tf,NULL);
sleep(3);
pthread_cond_signal(&cond);
pthread_join(tid,NULL);//Is 2nd parameter useful?
pthread_cond_destroy(&cond);
return 0;
}
复制代码
但是实际上,程序的输出是子线程立刻打印了"After main..."这句话。
这是为什么呢,哪个地方理解或者程序有错误? 还请帮忙纠正。
谢谢。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2