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()
orsigwait()
.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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With