凡在C中使用volatile关键字的地方 [英] Where all to use volatile keyword in C

查看:127
本文介绍了凡在C中使用volatile关键字的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道volatile关键字会阻止编译器优化变量并在每次读取时从内存中读取它。除了内存映射寄存器外,在什么情况下需要使用volatile?给定一个合格的编译器,在两种情况下我都必须将test_var声明为volatile吗?

I know volatile keyword prevents compiler from optimizing a variable and read it from memory whenever it is read. Apart from memory mapped registers, what are all the situations where we need to use volatile? Given a conforming compiler, do I have to declare test_var as volatile in both scenarios?

int test_var=100;


void func1()
{
    test_var++;
}



在file2.c



In file2.c

extern int test_var;

void func2()
{
    if(test_var==100)
    {
      ....
    }
}



2。



在文件1中。 c



2.

In file1.c

int test_var=100;

void func1()
{

}



在file2.c中



In file2.c

extern int test_var;

void func2()
{
    if(test_var==100)
    {
      ....
    }
}


推荐答案

内存映射的I / O是 仅在C中 volatile 的通用用法。*)

memory mapped I/O is the only generic use of volatile in C. *)

带有POSIX信号的 volatile 也可以与 sig_atomic_t 类型一起使用,像这样:

With POSIX signals, a volatile can also be used together with the type sig_atomic_t like this:

volatile sig_atomic_t signal_occured = 0;

您的两种情况均不要求 volatile 所有。如果您只想保证在不同编译单元之间更新了该值,请参见tofro的评论, extern 已经可以保证。特别是, volatile 不是用于C语言中线程同步的正确工具。它只会引入错误,因为正如您所说的那样,它 >确实需要对变量进行实际的读写访问,但不强制执行关于线程的正确排序(缺少内存障碍,请谷歌查询详细信息)。

Neither of your scenarios should require volatile at all. If all you're interested in is a guarantee that the value is updated between different compilation units, see tofro's comment, extern already guarantees that. Particularly, volatile is not the correct tool for thread synchronization in C. It would only introduce bugs, because, as you state it, it does require actual read and write accesses to the variable, but it does not enforce their proper ordering with respect to threads (it's missing memory barriers, google for details).

请注意,这与某些其他语言(其中 volatile 旨在在线程之间工作)不同。

Note that this is different from some other languages where volatile is designed to work between threads.

在嵌入式系统中,与数据结合使用时, volatile 可能足以在ISR(中断服务程序)和主程序之间进行通信自动读取/写入的类型,就像 sig_atomic_t 用于POSIX信号一样。为此,请查阅编译器的文档。

In an embedded system, volatile might be good enough for communicating between an ISR (interrupt service routine) and the main program, when combined with a data type that's read/written atomically, just like sig_atomic_t for POSIX signals. Consult the documentation of your compiler for that.

*)C标准提到了这一点,以及异步中断功能,仅在脚注中,因为内存映射的I / O不在该语言的范围内。该语言仅定义 volatile 的语义,使其适合内存映射的I / O。

*) The C standard mentions this, along with the use-case of "asynchronously interrupting functions", only in a footnote, because memory-mapped I/O is outside the scope of the language. The language just defines the semantics of volatile in a way that make it suitable for memory-mapped I/O.

这篇关于凡在C中使用volatile关键字的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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