【发布时间】:2015-03-09 10:36:55
【问题描述】:
我是条件变量的新手,如果不使用pthread_cond_broadcast(),就会出现死锁。
#include <iostream>
#include <pthread.h>
pthread_mutex_t m_mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
bool ready = false;
void* print_id (void *ptr )
{
pthread_mutex_lock(&m_mut);
while (!ready) pthread_cond_wait(&cv, &m_mut);
int id = *((int*) ptr);
std::cout << "thread " << id << '\n';
pthread_mutex_unlock(&m_mut);
pthread_exit(0);
return NULL;
}
这里的条件变了!
void go() {
pthread_mutex_lock(&m_mut);
ready = true;
pthread_mutex_unlock(&m_mut);
pthread_cond_signal(&cv);
}
如果我把go()的最后一行改成pthread_cond_broadcast(&cv);就可以了
int main ()
{
pthread_t threads[10];
// spawn 10 threads:
for (int i=0; i<10; i++)
pthread_create(&threads[i], NULL, print_id, (void *) new int(i));
go();
for (int i=0; i<10; i++) pthread_join(threads[i], NULL);
pthread_mutex_destroy(&m_mut);
pthread_cond_destroy(&cv);
return 0;
}
预期的答案(任意顺序)是
thread 0
....
thread 9
但是,在我的机器 (ubuntu) 上,它什么也没打印。 谁能告诉我原因?谢谢。
【问题讨论】:
-
是的。 _signal 唤醒等待列表中的任意线程。我错过了什么吗?
-
“但是……它什么也没打印。” 真的吗?乍一看,我很怀疑。假设 stdout 是行缓冲的(例如,终端),我理解为什么程序可能会打印 1 到 10 行输出,但不能打印零行输出。如果某些线程比
main快,那么至少其中一个线程将被发出信号并因此产生输出。如果某些线程比main慢,他们会发现ready已经准备好,并且每个线程都输出一行。
标签: c++ c pthreads mutex condition-variable