易失性,用于信号处理程序和多线程 [英] volatile for signal handler and multi-threading

查看:113
本文介绍了易失性,用于信号处理程序和多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据说信号处理程序需要volatile,例如

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();
    // ...
}

据说volatile在多线程中通常不使用.但是在多线程中类似上面的情况如何呢?

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;
    // ...
}

在两种情况下均应使用volatile关键字吗?编译器是否以相同的方式对待这两种情况?

Should the volatile keyword be used in both cases? Are the two cases treated the same way by compiler?

推荐答案

volatile用于确保从实际内存而不是从CPU寄存器读取变量的内容.

volatile is used to make sure that the contents of the variable is read from the actual memory rather than from a CPU register.

换句话说,无论何时外部"事件可能会更改变量的值,都应考虑使用volatile(外部"-在相关代码块外部).

In other words, whenever an "outside" event might change the value of a variable, you should consider using volatile ("outside" - as in, outside the relevant code block).

在两个示例中,您都将变量用作标志来表示行为发生变化.在两个示例中,此标志都由正在检查标志的循环外部"的事件控制.因此,两个示例都需要使用volatile关键字.

In both your examples, you are using the variable as a flag to signal a change in behavior. This flag, in both examples, is controlled by events "outside" the loop that that is reviewing the flag. For this reason, both examples require the use of the volatile keyword.

应注意,出于多种原因,volatile不会提供线程安全.为了确保对象是线程安全的,读/写操作必须是受保护的或原子的.

It should be noted volatile does not provide thread safety for a number of reasons. To make sure an object is thread safe, read/write operations must be either protected or atomic.

这篇关于易失性,用于信号处理程序和多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆