【发布时间】:2015-09-15 14:02:08
【问题描述】:
我对条件变量以及如何使用它们的理解显然存在缺陷。我的意图是拥有一个生产者和多个消费者线程,但我可以用一个生产者和一个消费者来证明我的问题。
有一个名为work 的共享变量受互斥锁和条件变量保护。生产者设置了work 变量并表示它已准备就绪,但消费者线程永远无法运行?
如果程序正常运行,它应该打印this line never get's printed,但我得到的是consumer never did work...giving up。任何帮助将不胜感激
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int work = 0;
void* consumer(void* ptr) {
pthread_mutex_lock(&mutex);
while(1) {
pthread_cond_wait(&cond, &mutex);
if (work == 0)
continue;
printf("this line never get's printed\n");
work = 0;
}
return NULL;
}
int main() {
pthread_t thr;
pthread_create(&thr, NULL, consumer, NULL);
sleep(1); /* give consumer moment to lock mutex */
for(int ndx=0; ndx < 50; ndx++) {
pthread_mutex_lock(&mutex);
if (work == 1) {
printf("consumer never did work...giving up\n");
return -1;
}
work = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}
return 0;
}
编译:
$ g++ -pthread simple.cpp -o simple
在 Debian 7.9 上运行(也在 CentOS 6.7 上重现)
$ getconf GNU_LIBPTHREAD_VERSION
NPTL 2.13
$ g++ --version
gcc version 4.7.2 (Debian 4.7.2-5)
【问题讨论】:
-
您的代码是 C,而不是 C++。建议使用 C 编译器(例如
gcc)而不是 C++ 编译器来编译它,无论如何我已经删除了你的 c++ 标签。 -
不要忽略检查函数调用的返回值。如果发生错误,您需要能够做出适当的响应,即使这只是干净地终止程序。
-
建议:阅读来自 LLNL 的Pthread Tutorial
-
volatile int work = 0; -
@JohnBollinger 如果 OP 使用 C++ 编译器,则代码为 C++。
标签: c++ multithreading pthreads mutex