【发布时间】:2017-11-28 07:43:44
【问题描述】:
我做了一个简单的实验来测试:
- 主线程创建子线程。
- 子线程等待主线程向条件变量发出信号。
- 主线程休眠 3 秒并发出“cond”信号。然后我希望子线程将从“cond_wait”中唤醒并打印。
代码:
#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 thread sleeps 3 seconds”。我哪里做错了?
谢谢。
【问题讨论】:
-
知道了,我还没有初始化两个pthread_xxxx_全局变量!刚刚修好了!
标签: c++ linux multithreading variables conditional