16

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 the atomic<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;
  ................
}
Fred Larson
  • 60,987
  • 18
  • 112
  • 174
MetallicPriest
  • 29,191
  • 52
  • 200
  • 356
  • Your question was answered ("Does volatile sig_atomic_t even work for multicore systems in the first place" - no), so you should accept provided answer. – Bulwersator Apr 20 '14 at 10:44

1 Answers1

21

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.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
  • 22
    Well 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). – R.. GitHub STOP HELPING ICE Dec 14 '11 at 20:17
  • 2
    as a reference to support @R.. see section 21.1.3 of The Linux Programming Interface – Nimjox May 10 '18 at 18:17