为什么我们使用 volatile 关键字?
可能的重复:
为什么存在 volatile?
我从未使用过它,但我想知道为什么人们使用它?它到底有什么作用?我搜索了论坛,发现只有 C# 或 Java 主题。
Possible Duplicate:
Why does volatile exist?
I have never used it but I wonder why people use it? What does it exactly do? I searched the forum, I found it only C# or Java topics.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
考虑这段代码,
当这个程序被编译时,编译器可能会优化这段代码,如果它发现程序从不曾经尝试更改
some_int
的值,所以它可能会想优化while
循环,将其从while(some_int == 100)
更改为 something ,这相当于while(true)
以便执行速度更快(因为while
循环中的条件似乎始终为true
)。 (如果编译器没有优化它,那么它必须在每次迭代中获取some_int
的值并将其与 100 进行比较,这显然有点慢。)然而,有时,(程序的某些部分)优化可能是不可取的,因为可能其他人正在从外部更改
some_int
的值编译器不知道的程序,因为它看不到它;但这就是你的设计方式。在这种情况下,编译器的优化将不会产生期望的结果!因此,为了确保获得所需的结果,您需要以某种方式阻止编译器优化
while
循环。这就是volatile
关键字发挥作用的地方。你需要做的就是这个,换句话说,我会解释如下:
易失性
告诉编译器,好吧,这就是
volatile
阻止编译器优化代码的方式。现在在网上搜索一些示例。引用自 C++ 标准 ($7.1.5.1/8)
相关主题:
使结构体变得易失性会使它的所有成员都易失性吗?
Consider this code,
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of
some_int
, so it may be tempted to optimize thewhile
loop by changing it fromwhile(some_int == 100)
to something which is equivalent towhile(true)
so that the execution could be fast (since the condition inwhile
loop appears to betrue
always). (if the compiler doesn't optimize it, then it has to fetch the value ofsome_int
and compare it with 100, in each iteration which obviously is a little bit slow.)However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of
some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!So, to ensure the desired result, you need to somehow stop the compiler from optimizing the
while
loop. That is where thevolatile
keyword plays its role. All you need to do is this,In other words, I would explain this as follows:
volatile
tells the compiler that,Well, that is how
volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.Quoting from the C++ Standard ($7.1.5.1/8)
Related topic:
Does making a struct volatile make all its members volatile?
http://en.wikipedia.org/wiki/Volatile_variable
编辑维基百科已经修复了有关 C++ 线程的废话,现在说
为了便于将来参考,下面的评论线程中关于
volatile
对于线程很有用的每一个声明要么是从其他语言完全错误的推断,要么是对非标准平台特定扩展(特别是 Microsoft)的引用。http://en.wikipedia.org/wiki/Volatile_variable
Edit Wikipedia has fixed the nonsense about threading for C++, and now says
For future reference, every claim in the comment thread below that
volatile
is useful for threading are either wholly incorrect extrapolations from other languages, or references to non-standard platform-specific extensions (specifically Microsoft).