Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing With Asynchronous Signals In Multi Threaded Program

The Linux Programming Interface Book has mentioned a method for dealing with asynchronous signals in a multi threaded program:

  • All threads block all of the asynchronous signals that the process might receive. The simplest way to do this is to block the signals in the main thread before any other thread are created. Each subsequently created thread will inherit a copy of the main thread's signal mask.
  • create a single dedicated thread that accepts incoming signals using sigwaitinfo(), sigtimedwait() or sigwait().

The advantage of this approach is that asynchronously generated signals are received synchronously. As it accepts incoming signals, the dedicated thread can safely modify shared variables (under mutex control) and call non-async-safe functions. It can also signal condition variables, and emply other thread and process communication and synchronization mechanisms.

Now the questions:

  1. when kernel wants to deliver signals it choose one of the threads inside process arbitrary. from where it can know to deliver signal to the dedicated thread?
  2. pthread API is non-aync-safe functions. so how we can use them inside signal handler?
like image 310
Majid Azimi Avatar asked Jun 03 '11 05:06

Majid Azimi


1 Answers

When the kernel delivers a process-directed signal, it chooses one of the threads that does not have the signal blocked. This means that it never chooses any of the threads apart from the signal-handling thread (which acts like it has the signal unblocked while it is blocked in sigwaitinfo() or similar). In other words: the kernel knows where to deliver the signal, because you have arranged things such that the signal-handling thread is the only thread that is ever allowed to deliver the signal to.

You do not use the pthreads API, or any non-async-signal-safe functions in a signal handler. The solution outlined does not handle the signals within signal handlers - it handles the signals within the normal execution flow of the signal-handling thread, after sigwaitinfo() returns. This allows it to access non-async-signal-safe functions, which is the whole point.

like image 72
caf Avatar answered Nov 16 '22 04:11

caf