我正在阅读Java并发实践,在“16.1.3 500字以内的Java内存模型”中,它说:
The Java Memory Model is specified in terms of actions, which include reads and writes to variables, locks and unlocks of monitors, and starting and joining with threads. The JMM defines a partial ordering called happens-before on all actions within the program. To guarantee that the thread executing action B can see the results of action A (whether or not A and B occur in different threads), there must be a happens-before relationship between A and B. In the absence of a happens-before ordering between two operations, the JVM is free to reorder them as it pleases.
Even though actions are only partially ordered, synchronization actions—lock acquisition and release, and reads and writes of volatile variables—are totally ordered. This makes it sensible to describe happens-before in terms of “subsequent” lock acquisitions and reads of volatile variables.
关于“部分排序”,我找到了this和 this ,但我不太明白“尽管操作只是部分有序的,但同步操作(锁获取和释放以及 volatile 变量的读写)是完全有序的。”。 “同步操作完全有序”是什么意思?
最佳答案
分析“同步 Action 是完全有序的”语句:
- “同步 Action ”是一个集合
S
程序操作( Action ) - 我们有关系
R
超过设置S
:这是发生在之前的关系。也就是说,给定程序语句a
和b
,aRb
当且仅当a
发生在b
之前.
那么该语句所说的是“关系 R
是 S 上的总计”。
“关系R
总和超过S
”,意味着每两个操作a,b
来自集合S
(与 a!=b
),或者 aRb
,或bRa
。也就是说,要么 a
发生在b
之前,或b
发生在a
之前。
如果我们定义集合S
作为在同一锁定对象上执行的所有锁定获取和锁定释放的集合 X
;然后设置S
完全按照发生之前关系排序:令为 a
锁的获取X
由线程执行T1
,和b
线程执行的锁获取T2
。然后 a
发生在b
之前(如果T1先获取锁,则T1需要先释放锁,然后T2才能获取锁);或b
发生在a
之前(如果 T2 先获取锁)。
注意:并非所有关系都是完整的。
例如,关系 <=
是实数的总和。也就是说,对于每对 a,b
的实数,确实 a<=b
或b<=a
。这里的总顺序意味着给定任意两个项目,我们始终可以决定哪一个先出现。给定的关系。
但是关系P
:“是……的祖先”,并不是所有人类集合的总关系。当然,对于某些人类来说a,b
确实是 aPb
( a
是 b
的祖先),或 bPa
( b
是 a
的祖先)。但对于大多数人来说,都不是 aPb
也不bPa
是真的;也就是说,我们不能使用关系来决定哪个项目“首先”(系谱术语)。
返回程序语句,发生之前关系 R
显然是部分的,在所有程序语句的集合上(就像在“ancestor-of”示例中):给定不同步的操作 a,b
(在没有正确同步的情况下,由不同线程执行的任何操作), aRb
都不是也不bRa
成立。
关于java - "synchronization actions are totally ordered"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59896563/