Skip site navigation (1)Skip section navigation (2)
Date:      Thu, 3 Jan 2008 17:18:21 -0800
From:      Alfred Perlstein <alfred@freebsd.org>
To:        Ivan Voras <ivoras@freebsd.org>
Cc:        freebsd-threads@freebsd.org
Subject:   Re: Threads and signals
Message-ID:  <20080104011821.GD76698@elvis.mu.org>
In-Reply-To: <fljin9$crb$1@ger.gmane.org>
References:  <fljin9$crb$1@ger.gmane.org>

next in thread | previous in thread | raw e-mail | index | archive | help
* Ivan Voras <ivoras@freebsd.org> [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



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20080104011821.GD76698>