From owner-freebsd-threads@FreeBSD.ORG Fri Jan 4 01:20:47 2008 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 8FCE516A41A for ; Fri, 4 Jan 2008 01:20:47 +0000 (UTC) (envelope-from bright@elvis.mu.org) Received: from elvis.mu.org (elvis.mu.org [192.203.228.196]) by mx1.freebsd.org (Postfix) with ESMTP id 7B92D13C45A for ; Fri, 4 Jan 2008 01:20:47 +0000 (UTC) (envelope-from bright@elvis.mu.org) Received: by elvis.mu.org (Postfix, from userid 1192) id 8982F1A4D82; Thu, 3 Jan 2008 17:18:21 -0800 (PST) Date: Thu, 3 Jan 2008 17:18:21 -0800 From: Alfred Perlstein To: Ivan Voras Message-ID: <20080104011821.GD76698@elvis.mu.org> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.4.2.3i Cc: freebsd-threads@freebsd.org Subject: Re: Threads and signals 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: Fri, 04 Jan 2008 01:20:47 -0000 * Ivan Voras [080103 13:03] wrote: > Hi, > > How do threads interact with signals? In particular, if I have a "main" > process thread (the one started by main()) which generates items for a > mutex-protected queue which are consumed by a worker thread, and I need > to insert an item in the queue from the signal handler, am I correct > that doing pthread_mutex_lock() from the signal handler could deadlock > if the signal handler is executed by any of the threads (and the mutex > is non-recursive)? > > How is this solved in general? By recursive mutexes? You need to block/unblock signals or use sigwait. So basically your code will look something like: main() { defer_signals(); signal(SIGWHATEVER, &handler); make_threads(); for ( ;; ) { do_stuff(); undefer_signals(); /* right here "handler" may be called */ defer_signals(); } } Another option is to have one of your threads use sigwait() and do the operation synchronously. Another is to write(2) to a pipe(2) from within your signal handler that one of your threads is select(2)/poll(2)/kevent(2) against, then the selecting thread can read the byte, thereby clearing the event and then queue the workitem synchronously. -- - Alfred Perlstein