Join GitHub today
GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together.Sign up
Thread.sigmask not working under pthreads #4127
Original bug ID: 4127
Thread.sigmask seems to be ignored.
Comment author: @xavierleroy
I've been sleeping on this PR for way too long, so I'm un-assigning it from me.
Here is my analysis. The kernel delivers the signal to one of the threads that doesn't block it. However, if this thread is outside a blocking section, it cannot act on it immediately and instead records the signal as pending in a global data structure. Other threads poll this data structure periodically and can decide to handle the signal even if they block it themselves (or, more exactly, blocked it at the time the signal was received). In effect, Thread.sigmask is useless.
Comment author: @diml
From my experience, the most reliable way to deal with signals in a multi-threaded program is to handle them from a single thread with [Thread.wait_signal] and redirect signals to this particular thread if they are received from another thread, using a pure C signal handler.
This is from a project where I did this:
-----[ ml code ]-----
external init_signal_manager_thread : unit -> unit = "lt_term_init_signal_manager_thread"
let signal_manager_loop () =
let init () = ignore (Thread.create signal_manager_loop () : Thread.t)
-----[ C code ]-----
static pthread_t signal_manager_thread = 0;
CAMLprim value lt_term_init_signal_manager_thread()
static void handle_signal(int signum)
Then [process_signal] is free to handle or deliver the signal to another thread via some other mechanism. I think that this is even better than handling signals directly in a single-thread application, since you know exactly the context in which the code processing the signal will be executed.
Fixing this ticket seems like it would be complicated, and even if it's fixed it doesn't help programmers as they have to be extremely careful about what they do from a signal handler. I'm wondering if it wouldn't be worth simply providing an API to handle signal in the way I describe and document that this is the recommended way to handle signals in multi-threaded applications.