use*_*598 3 c c++ multithreading volatile
据说信号处理程序需要volatile,例如,
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();
// ...
}
Run Code Online (Sandbox Code Playgroud)
据说volatile通常不用于多线程.但是多线程中类似的情况怎么样:
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;
// ...
}
Run Code Online (Sandbox Code Playgroud)
两种情况下都应该使用volatile关键字吗?这两种情况是否由编译器以相同的方式处理?
允许您从信号处理程序修改的唯一非本地值是类型volatile sig_atomic_t和原子类型.特别是,写你volatile int是不是允许的,如果你的信号处理程序运行你不确定的行为.