Date: Mon, 24 Dec 2007 09:48:52 +0800 From: David Xu <davidxu@FreeBSD.org> To: Ivan Voras <ivoras@FreeBSD.org> Cc: freebsd-threads@FreeBSD.org Subject: Re: Proper use of condition variables? Message-ID: <476F1004.2020902@freebsd.org> In-Reply-To: <fkk5ht$gsj$1@ger.gmane.org> References: <fkk5ht$gsj$1@ger.gmane.org>
index | next in thread | previous in thread | raw e-mail
Ivan Voras wrote:
> 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);
>
use :
while (STAILQ_EMPTY(&thr->queue))
pthread_cond_wait(&thr->queue_cv, &thr->queue_mtx);
It is possible pthread_cond_wait returned with surplus wakeup, e.g
kernel signal etcs...
> 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].
help
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?476F1004.2020902>
