Threads and signals
Alfred Perlstein
alfred at freebsd.org
Thu Jan 3 17:20:47 PST 2008
* Ivan Voras <ivoras at 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
More information about the freebsd-threads
mailing list