gpt4 book ai didi

java - 没有 volatile 变量的同步中断

转载 作者:行者123 更新时间:2023-12-03 13:09:22 26 4
gpt4 key购买 nike

如果程序员忘记添加 volatile,我想了解从缓存的观点(MESI 协议(protocol))会发生什么。用于同步的变量的关键字。

以下代码片段在一些迭代后简单地停止。我知道这是因为 2 个线程之一(假设 THREAD 0)没有看到对 current 的更新。 THREAD 1 的变量由 getNext() 完成,因此它会一直循环。

但是,我不明白为什么会这样。线程 0 在 current 上循环并且应该在某个时刻看到缓存行已被线程 1 更新(缓存行切换到修改状态)并在内存总线上发出“读取”消息以在其本地缓存中获取它。添加 volatile修改为 current变量将使一切正常。

发生了什么阻止 THREAD 0 继续执行?

引用:Memory Barriers: a Hardware View for Software Hackers

public class Volatile {
public static final int THREAD_0 = 0;
public static final int THREAD_1 = 1;
public static int current;
public static int counter = 0;

public static void main(String[] args) {
current = 0;

/** Thread 0 **/
Thread thread0 = new Thread(() -> {
while(true) { /** THREAD_0 */
while (current != THREAD_0);

counter++;
System.out.println("Thread0:" + counter);

current = getNext(THREAD_0);
}
});

/** Thread 1 **/
Thread thread1 = new Thread(() -> {
while(true) { /** THREAD_1 */
while (current != THREAD_1);

counter++;
System.out.println("Thread1:" + counter);

current = getNext(THREAD_1);
}
});

thread0.start();
thread1.start();
}

public static int getNext(int threadId) {
return threadId == THREAD_0 ? THREAD_1 : THREAD_0;
}
}

最佳答案

不同的处理器架构可以具有不同程度的高速缓存一致性。有些可能非常小,因为目标是最大化吞吐量,并且不必要地将缓存与内存同步会拖累它。当 Java 检测到需要协调时,它会施加自己的内存屏障,但这取决于程序员是否遵守规则。

如果程序员没有添加变量可以跨线程共享的指示(例如使用 synchronized 或 volatile 关键字),则允许 JIT 假设没有其他线程正在修改该变量,并且可以相应地进行优化。测试该变量的字节码可以彻底重新排序。如果 JIT 对代码重新排序足够多,那么硬件检测到修改并获取新值的时间可能无关紧要。

引用 Java Concurrency in Practice 3.1:

In the absence of synchronization, the compiler, processor, and runtime can do some downright weird things to the order in which operations appear to execute. Attempts to reason about the order in which memory actions "must" happen in insufficiently synchronized multithreaded programs will almost certainly be incorrect.



(JCIP 书中有几个地方证明推理不充分同步的代码是徒劳的。)

关于java - 没有 volatile 变量的同步中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41090273/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com