Proper usage of volatile sig_atomic_t
Unless your program is multithreaded, signal handlers never run concurrently with other code in your program, and they certainly never run concurrently with the code they've interrupted. Your code is fine as long as the signal sig
is masked for the duration of the signal handler.
MetallicPriest
Updated on July 21, 2022Comments
-
MetallicPriest almost 2 years
According to this site, one can use variables of type
volatile sig_atomic_t
inside a signal handler. Now my question is, would for example something like the following code still be atomic and thus introduce no race conditions?Assume that we are using a multicore processor (EDIT: running a multithreaded program). Does
volatile sig_atomic_t
even work for multicore systems in the first place or should we use theatomic<unsigned int>
of C++11 for signal handlers on a multicore system (EDIT: running a multithreaded program)?volatile sig_atomic_t a; static void signal_handler(int sig, siginfo_t *si, void *unused) { int b; ................ b = ...; a = a | b; ................ }
-
R.. GitHub STOP HELPING ICE over 12 yearsWell then
sig_atomic_t
has nothing to do with the multi-threaded aspect. It's only relevant for ensuring atomicity of operations interrupted by a signal handler in the same thread, i.e. to ensure that you don't get a sequence like: (1) main program flow writes high byte, (2) signal handler writes a new value to the whole variable and returns, (3) main program flow writes low byte (due to interruption by a signal between partial writes). -
Nimjox about 6 yearsas a reference to support @R.. see section 21.1.3 of The Linux Programming Interface