setitimer, SIGALRM & multithread process (linux, c) setitimer, SIGALRM & multithread process (linux, c) multithreading multithreading

setitimer, SIGALRM & multithread process (linux, c)


From signal(7) man page:

A process-directed signal may be delivered to any one of the threads that does not currently have the signal blocked. If more than one of the threads has the signal unblocked, then the kernel chooses an arbitrary thread to which to deliver the signal.

Now, alarm(2) man page says that:

alarm() arranges for a SIGALRM signal to be delivered to the process in seconds seconds.

So, the signal is delivered to a process (a signal might be directed at certain thread too) and thus you do not know which of the threads will receive it.

The same with setitimer(2):

When any timer expires, a signal is sent to the process, and the timer (potentially) restarts.

You could block SIGALARM in all your threads except one, then you could be certain that it will be delivered to that only thread. Assuming you are using pthreads, you can block signals with pthread_sigmask().


There was interesting topic in LKML in 2010 https://lkml.org/lkml/2010/4/11/81: "setitimer vs. threads: SIGALRM returned to which thread? (process master or individual child)" by Frantisek Rysanek (cz). Author says that setitimer used per-thread signals at least in times before Fedora 5:

... setitimer() had per-thread granularity. It used to deliver a SIGALRM from the timer to the particular thread that called setitimer().

But in more recent Fedoras the behavior was changed ("man pthreads", ..."Threads do not share interval timers (fixed in kernel 2.6.12).")

In the topic, Andi Kleen (Intel) recommends to switch to "POSIX timers (timer_create)"; and in ML thread Davide Libenzi suggests use of timerfd (timerfd_create, timerfd_settime) on non-ancient Linuxes.