gpt4 book ai didi

java - 是否保证所有参与线程的 compareAndSwap 都不会失败?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:25:44 24 4
gpt4 key购买 nike

假设一些“N”个线程正在尝试 CAS 一个 AtomicInteger 变量,是否保证 CAS 必须恰好一个线程成功?

是否有可能所有“N”个线程都尝试失败?

最佳答案

compareAndSet 旨在由硬件实现,因此行为将取决于您运行的特定硬件。来自 java.util.concurrent.atomic:

This method (which varies in argument types across different classes) atomically sets a variable to the updateValue if it currently holds the expectedValue, reporting true on success. The classes in this package also contain methods to get and unconditionally set values, as well as a weaker conditional atomic update operation weakCompareAndSet described below.

The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors. However on some platforms, support may entail some form of internal locking. Thus the methods are not strictly guaranteed to be non-blocking -- a thread may block transiently before performing the operation.

假设是典型的硬件,第一个到达底层硬件指令的线程将执行原子 CAS(假设它具有正确的初始值),所有其他线程都将失败。

如果底层硬件允许所有竞争线程失败,那么 Java API 中似乎没有任何东西需要不同的行为。但是,对于所有线程都可能失败的 CAS 可能会导致活锁情况和非确定性行为,因此任何实现 CAS 的硬件都可能保证一个线程会成功。

关于java - 是否保证所有参与线程的 compareAndSwap 都不会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14453759/

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