I've clearly developed a flawed understanding of condition variables and how to use them. My intention is to have a single producer and multiple consumer threads but I can demonstrate my problem with a single producer and a single consumer.
There is a single shared variable called work
that is protected with a mutex and a condition variable. The producer sets the work
variable and signals it is ready, but the consumer thread never get's to run?
If the program works correctly, it should print this line never get's printed
, but instead I get consumer never did work...giving up
. Any assistance would be greatly appreciated
#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;
}
Compiled with:
$ g++ -pthread simple.cpp -o simple
Running on Debian 7.9 (also reproduced on CentOS 6.7)
$ getconf GNU_LIBPTHREAD_VERSION
NPTL 2.13
$ g++ --version
gcc version 4.7.2 (Debian 4.7.2-5)