Do I need to lock a shared variable of type volatile sig_atomic_t in a multithreaded program?

Q1) Do I need to lock a shared variable of type volatile sig_atomic_t in a multithreaded program?
Q2) also, is it safe to call pthread_mutex_lock or pthread_rwlock_wrlock in a signal handler?

the reason I ask this is because I have a multithreaded server and when I type ctrl-c which generates SIGINT, I want the signal handler to modify a shared boolean variable exitFlag from false to true so that the server thread would upon looking the next time at the shared variable determine that it is time to exit and return cleanly(that means, stop accepting any new connections and join any threads handling existing transactions after they have completed).
Last edited on
q1) no, locking won't make a difference
q2) i think is now irrelevant.
@jsmith
Q1) is it because read and write access to the variable is always atomic?

but according to here:
http://cboard.cprogramming.com/c-programming/102697-sig_atomic_t-avoid-mutex-critical-sections.html
http://cboard.cprogramming.com/c-programming/129254-pthread-shared-variables.html

they say that

sig_atomic_t doesn't really have anything to do with multi-threaded programming. The C standard says that any access to a global within a signal handler must be a write access and the type must be "volatile sig_atomic_t". The standard doesn't say much else on the subject.



Writing to a volatile sig_atomic_t is the only global variable access allowed by Posix in a signal handler. For C++0x we have:
When the processing of the abstract machine is interrupted by receipt of a signal, the values of objects which are neither
— of type volatile std::sig_atomic_t nor
— lock-free atomic objects (29.4)
are unspecified, and the value of any object not in either of these two categories that is modified by the handler becomes undefined.
Only good for signal handlers.
Last edited on
Let's say I have a volatile sig_atomic_t variable that currently has the value 42. If I set the value of this variable to 99 in thread A, then sig_atomic_t guarantees that thread B will see either the value 42 or the value 99. That's all sig_atomic_t gives you.

Essentially what it means is that the value is written to memory in a single processor instruction.

Topic archived. No new replies allowed.