Proper use of condition variables?

Ivan Voras ivoras at
Sat Dec 22 16:08:34 PST 2007


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) {
	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);



On the server side, it's like this:

[X]	pthread_mutex_lock(&thr->queue_mtx);
	STAILQ_INSERT_TAIL(&thr->queue, job, linkage);

The two lines that deadlock are marked with [X].

More information about the freebsd-threads mailing list