Date: Sun, 23 Dec 2007 00:10:53 +0100 From: Ivan Voras <ivoras@freebsd.org> To: freebsd-threads@freebsd.org Subject: Proper use of condition variables? Message-ID: <fkk5ht$gsj$1@ger.gmane.org>
next in thread | raw e-mail | index | archive | help
Hi, I'm implementing what is basically a producer-consumer setup in which two threads communicate only by a message queue. The idea is that the consumer waits on a condition variable until something gets in the queue, then takes it out and processes it. Unfortunately the program deadlocks with the provider waiting in pthread_mutex_lock(queue_mtx) and the consumer waiting in pthread_cond_wait(queue_cv, queue_mtx). This is on RELENG_7. Am I misreading how pthread_cond_wait should behave? I thought it should release the mutex until the cv gets signaled. On the consumer side, the code looks like this: while (1) { pthread_mutex_lock(&thr->queue_mtx); if (STAILQ_EMPTY(&thr->queue)) [X] pthread_cond_wait(&thr->queue_cv, &thr->queue_mtx); job = STAILQ_FIRST(&thr->queue); STAILQ_REMOVE_HEAD(&thr->queue, linkage); pthread_mutex_unlock(&thr->queue_mtx); process(job); } On the server side, it's like this: [X] pthread_mutex_lock(&thr->queue_mtx); STAILQ_INSERT_TAIL(&thr->queue, job, linkage); pthread_mutex_unlock(&thr->queue_mtx); pthread_cond_signal(&thr->queue_cv); The two lines that deadlock are marked with [X].
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?fkk5ht$gsj$1>