From owner-freebsd-threads@FreeBSD.ORG Mon Dec 24 01:47:52 2007 Return-Path: Delivered-To: freebsd-threads@hub.freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id 796C716A419; Mon, 24 Dec 2007 01:47:52 +0000 (UTC) (envelope-from davidxu@FreeBSD.org) Received: from freefall.freebsd.org (freefall.freebsd.org [IPv6:2001:4f8:fff6::28]) by mx1.freebsd.org (Postfix) with ESMTP id 85A1713C448; Mon, 24 Dec 2007 01:47:52 +0000 (UTC) (envelope-from davidxu@FreeBSD.org) Received: from apple.my.domain (root@localhost [127.0.0.1]) by freefall.freebsd.org (8.14.2/8.14.2) with ESMTP id lBO1llBu031215; Mon, 24 Dec 2007 01:47:48 GMT (envelope-from davidxu@freebsd.org) Message-ID: <476F1004.2020902@freebsd.org> Date: Mon, 24 Dec 2007 09:48:52 +0800 From: David Xu User-Agent: Thunderbird 2.0.0.9 (X11/20071211) MIME-Version: 1.0 To: Ivan Voras References: In-Reply-To: Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Cc: freebsd-threads@FreeBSD.org Subject: Re: Proper use of condition variables? X-BeenThere: freebsd-threads@freebsd.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: Threading on FreeBSD List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 24 Dec 2007 01:47:52 -0000 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].