Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile for signal handler and multi-threading

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?

like image 971
user2847598 Avatar asked Dec 07 '22 19:12

user2847598


1 Answers

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.

like image 173
Kerrek SB Avatar answered Jan 12 '23 03:01

Kerrek SB