It is said volatile is needed for signal handler, e.g.,
volatile int flag = 1; // volatile is needed here?
void run() {
while(flag) { /* do someting... */ }
}
void signal_handler(int sig) {
flag = 0;
}
int main() {
signal(SIGINT, sig_handler);
run();
// ...
}
It is said volatile is often not used in multithreading. But how about the similar case like above in multithreading:
int flag = 1; // is volatile needed here?
void thread_function() {
while(flag) { /* do someting... */ }
}
int main() {
// pthread_create() to create thread_function()...
sleep(10); // let thread_function run for 10 seconds
flag = 0;
// ...
}
Should the volatile keyword be used in both cases? Are the two cases treated the same way by compiler?
The only non-local values you are allowed to modify from a signal handler are those of type volatile sig_atomic_t
, and atomic types. In particular, writing to your volatile int
is not allowed, and if your signal handler runs you have undefined behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With