gpt4 book ai didi

java - 不懂Java原子包中的CAS操作

转载 作者:搜寻专家 更新时间:2023-11-01 00:56:15 25 4
gpt4 key购买 nike

我正在研究 Java 书中的并发包。我不太明白这本书中关于 CAS 操作的内容。以下代码示例是本书中的线程安全 counter 类。

public class Counter{
private AtomicInteger count = new AtomicInteger();
public void increment(){
count.getAndIncrement(); //atomic operation
}
....
}

这本书是这样说的。

In reality, even a method such as getAndIncrement() still takes several steps to execute. The reason this implementation is now thread-safe is something called CAS. CAS stands for Compare And Swap. Most modern CPUs have a set of CAS instructions. A basic outline of what is happening now is as follows:

  1. The value stored in count is copied to a temporary variable.
  2. The temporary variable is incremented.
  3. Compare the value currently in count with the original value. If it is unchanged, then swap the old value for the new value.

好的,我明白它所说的关于多个步骤的意思了。我不太明白在列举的步骤中发生了什么。

  1. The value stored in count is copied to a temporary variable.

临时变量在哪里?它在主存储器中,寄存器吗?或者这是特定于 CPU 架构的?

  1. Compare the value currently in count with the original value. If it is unchanged, then swap the old value for the new value.

原始值存储在哪里?它不能是临时变量。那个正在修改,对吧?我错过了什么?

谢谢

最佳答案

被比较的值被加载到两个以上的寄存器中(在你的例子中是三个)。然后它可能会使用类似 CMPXCHG8B 的指令这被描述(部分)为

Compare EDX:EAX with m64. If equal, set ZF and load ECX:EBX into m64. Else, clear ZF and load m64 into EDX:EAX.

上面的第三个值可能在不同的寄存器中,比如 ECX(或 EBX)或其他一些位置(只是不是 EAXEDX)。您可以引用 Compare and Swap 上的维基百科条目对于其他实现(不一定使用汇编程序)。

关于java - 不懂Java原子包中的CAS操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27810235/

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