易失性:为什么要阻止编译器重新排序代码 [英] Volatile: why prevent compiler reorder code
问题描述
在java中,据我所知,volatile变量使一个线程直接读/写到主CPU(不在每个线程的缓存中),因此将其更改显示给其他线程。
In java, with my knowledge, volatile variable make a thread reads/writes directly to main CPU (not in cache of each thread), so make its change visibles to other threads.
我不知道的是:所以,为什么这个工作(volatile)会阻止编译器/ CPU重新排序代码语句。
The thing I don't know is : So, why this work (of volatile) can prevent compiler/CPU reorder statement of code.
谢谢: )
推荐答案
这是一个非常好的例子,说明禁止重新排序旨在解决的问题(摘自这里):
Here is a very good example illustrating the issue the prohibition on reordering is aimed to address (taken from here):
class VolatileExample {
int x = 0;
volatile boolean v = false;
public void writer() {
x = 42;
v = true;
}
public void reader() {
if (v == true) {
//uses x - guaranteed to see 42.
}
}
}
在此示例中, v
是易变的,但 x
不是。如果同时执行writer和reader并且读者看到 v
设置为 true
, x
保证 42
。在Java-5之前,编译器可以自由地将写入重新排序到 x
和 v
,所以你可以看到 x
在零之后你已经看到 v
设置为真
。这令人困惑,并导致微妙的错误。 Java-5内存模型通过使易失性写入几乎等同于同步来解决此问题。
In this example, v
is volatile, but x
is not. If writer and reader are executed concurrently and the reader sees v
set to true
, x
is guaranteed to be 42
. Prior to Java-5, compiler was free to re-order the writes to x
and v
, so you could see x
at zero after you've seen v
set to true
. This was confusing, and lead to subtle errors. Java-5 memory model addressed this issue by making volatile writes almost equivalent to synchronization.
这篇关于易失性:为什么要阻止编译器重新排序代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!