From owner-freebsd-threads@FreeBSD.ORG Sun Dec 23 00:08:34 2007 Return-Path: Delivered-To: freebsd-threads@freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id 38E5416A481 for ; Sun, 23 Dec 2007 00:08:34 +0000 (UTC) (envelope-from gofdt-freebsd-threads@m.gmane.org) Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by mx1.freebsd.org (Postfix) with ESMTP id 046E313C45B for ; Sun, 23 Dec 2007 00:08:33 +0000 (UTC) (envelope-from gofdt-freebsd-threads@m.gmane.org) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1J6DY9-0007cO-Al for freebsd-threads@freebsd.org; Sat, 22 Dec 2007 23:14:33 +0000 Received: from cmung2217.cmu.carnet.hr ([193.198.136.185]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 22 Dec 2007 23:14:33 +0000 Received: from ivoras by cmung2217.cmu.carnet.hr with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 22 Dec 2007 23:14:33 +0000 X-Injected-Via-Gmane: http://gmane.org/ To: freebsd-threads@freebsd.org From: Ivan Voras Date: Sun, 23 Dec 2007 00:10:53 +0100 Lines: 35 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@ger.gmane.org X-Gmane-NNTP-Posting-Host: cmung2217.cmu.carnet.hr User-Agent: Thunderbird 1.5.0.13 (Windows/20070809) X-Enigmail-Version: 0.94.1.0 Sender: news Subject: 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: Sun, 23 Dec 2007 00:08:34 -0000 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].