挥发性变量和订购前发生的事情 [英] Volatile Variables and Happens before ordering
问题描述
我有两个主题:
线程:1
a = 1;
x = b;
线程:2
b = 1
y = a
此处声明a和b易挥发。我不明白在a = 1之间如何创建发生前边缘;和y = a;在x = b之间;和b = 1;
Here a and b are declared volatile. I did not understand how a "happens-before" edge is created between a = 1; and y = a; and between x = b; and b = 1;
我知道通过使用volatile变量可以防止从线程缓存中读取过时值。但是,在订购之前,如何确保变量发生变化。
I understand that by using volatile variable one can prevent reading stale values from thread cache. But how can a volatile variable ensure happens-before ordering.
具体来说,我不明白这一点:
Specifically, I did not understand this:
写入易失性字段在每次后续读取
相同字段之前发生
。
a write to a volatile field happens before every subsequent read of the same field.
Hoe有效吗?
推荐答案
对易失性字段的写入发生在每次后续读取同一字段之前。
a write to a volatile field happens before every subsequent read of the same field.
这里的重要词是后续。
这是Java语言的相关部分规范 17.4.4同步订单:
Here's the relevant bit of the Java Language Specification 17.4.4 Synchronization Order:
每次执行都有一个同步顺序。同步顺序是执行的所有同步动作的总顺序。对于每个线程t,t中同步动作(第17.4.2节)的同步顺序与t的程序顺序(第17.4.3节)一致。
同步动作引发与动作的同步关系,定义如下:
Every execution has a synchronization order. A synchronization order is a total order over all of the synchronization actions of an execution. For each thread t, the synchronization order of the synchronization actions (§17.4.2) in t is consistent with the program order (§17.4.3) of t. Synchronization actions induce the synchronized-with relation on actions, defined as follows:
- [...]
- 对volatile变量(第8.3.1.4节)的写入v与任何线程对v的所有后续读取同步(其中后续根据同步顺序定义)。
注意最后一部分。所以它说如果你考虑程序动作的任何总顺序,那么读取总顺序中的一个易变量而不是写入的任何读取都不能错过写入。
Note the last part. So it's saying that if you consider any total ordering of the actions of the program, any read of a volatile variable which comes later in that total ordering than a write can't "miss" the write.
这篇关于挥发性变量和订购前发生的事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!