问题描述
C#和Java都定义了
* volatile读取具有获取语义
* volatile写入具有发布语义
我的问题是:
volatile背后的原因
语义植根于
Both C# and Java define that
* volatile reads have acquire semantics
* volatile writes have release semantics
My questions are:
The reasoning behind the volatile
semantic is rooted in the Java Memory Model, which is specified in terms of actions:
- reads and writes to variables
- locks and unlocks of monitors
- starting and joining with threads
The Java Memory Model defines a partial ordering called happens-before for the actions which can occur in a Java program. Normally there is no guarantee, that threads can see the results of each other actions.
Let's say you have two actions A and B. In order to guarantee, that a thread executing action B can see the results of action A, there must be a happens-before relationship between A and B. If not, the JVM is free to reorder them as it likes.
A program which is not correctly synchronized might have data races. A data race occurs, when a variable is read by > 1 threads and written by >= 1 thread(s), but the read and write actions are not ordered through the happens-before ordering.
Hence, a correctly synchronized program has no data races, and all actions within the program happen in a fixed order.
So actions are generally only partially ordered, but there is also a total order between:
- lock acquisition and release
- reads and writes to volatile variables
These actions are totally ordered.
Regarding your questions:
- With the happen-before relationship you have an alternative definition of
volatile
- Reversing the order would not make sense to the definition above, especially since there is a total order involved.
Source: Java Concurrency in Practice
这篇关于Java和C#中的volatile语义背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!