可能的重复: 为什么挥发性存在?

我从来没用过,但我想知道人们为什么要用它?它到底是做什么的?我搜索了论坛,我发现只有c#或Java主题。


在计算机编程中,特别是在C、c++和c#编程语言中,使用volatile关键字声明的变量或对象通常具有与优化和/或线程相关的特殊属性。一般来说,volatile关键字是为了防止(伪)编译器对假定变量的值不能“自行”改变的代码应用任何优化。(c)维基百科

http://en.wikipedia.org/wiki/Volatile_variable

考虑这段代码,

int some_int = 100;

while(some_int == 100)
{
   //your 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 the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

然而,有时,优化(你程序的某些部分)可能是不可取的,因为可能是其他人从程序外部改变了some_int的值,而编译器并不知道,因为它看不到它;但这是你设计出来的。在这种情况下,编译器的优化不会产生预期的结果!

因此,为了确保得到预期的结果,您需要以某种方式阻止编译器优化while循环。这就是volatile关键字发挥作用的地方。你只需要这样做,

volatile int some_int = 100; //note the 'volatile' qualifier now!

换句话说,我将这样解释:

Volatile告诉编译器,

"嘿,编译器,我是易变的,你 我可以被某个XYZ改变 你甚至都没有意识到那 XYZ可以是任何东西。也许一些 这个星球外的外星人喊道 程序。也许是一些闪电,一些 形式中断,火山爆发等可以 我变异。也许吧。你永远不知道谁 会改变我!所以,你 无知者,别再玩无所不知了 天啊,别碰密码 我现在所在的地方。没事吧?”

这就是volatile阻止编译器优化代码的原因。现在在网上搜索一些例子。


引用c++标准($7.1.5.1/8)

(. .不稳定的是一种暗示 实现以避免侵略性 涉及对象的优化 因为对象的值可能 用无法被探测到的方法改变 实现。[…]

相关主题:

使结构体为volatile是否使其所有成员都为volatile?