x86 CMPXCHG是原子的,如果是这样,为什么它需要LOCK? [英] Is x86 CMPXCHG atomic, if so why does it need LOCK?
问题描述
该指令可用于
LOCK
前缀允许原子地执行指令。
This instruction can be used with a
LOCK
prefix to allow the instruction to be executed atomically.
我的问题是
-
CMPXCHG
是否可以使用内存地址进行操作?从文档看来,似乎没有,但是没有人能确认仅适用于寄存器中的实际值,而不适用于存储器地址吗?
Can
CMPXCHG
operate with memory address? From the document it seems not but can anyone confirm that only works with actual VALUE in registers, not memory address?
如果 CMPXCHG
不是原子的,必须通过 LOCK CMPXCHG
(带有 LOCK
前缀),完全引入这样一条指令的目的是什么?
If CMPXCHG
isn't atomic and a high level language level CAS has to be implemented through LOCK CMPXCHG
(with LOCK
prefix), what's the purpose of introducing such an instruction at all?
推荐答案
您正在将高级锁与恰好名为 LOCK
的低级CPU功能混在一起。
You are mixing up high-level locks with the low-level CPU feature that happened to be named LOCK
.
无锁算法试图避免的高级锁可以保护任意代码段,这些代码段的执行可能需要花费任意时间,因此,这些锁将不得不将线程置于等待状态,直到可用该锁为止操作,例如
The high-level locks that lock-free algorithms try to avoid can guard arbitrary code fragments whose execution may take arbitrary time and thus, these locks will have to put threads into wait state until the lock is available which is a costly operation, e.g. implies maintaining a queue of waiting threads.
这与CPU的 LOCK
前缀功能完全不同,它可以保护等待的线程。仅一条指令,因此可能仅在一条指令的持续时间内就拥有其他线程。由于这是由CPU本身实现的,因此不需要额外的软件。
This is an entirely different thing than the CPU LOCK
prefix feature which guards a single instruction only and thus might hold other threads for the duration of that single instruction only. Since this is implemented by the CPU itself, it doesn’t require additional software efforts.
因此,开发无锁算法的挑战并不在于完全消除同步,它归结为将代码的关键部分简化为单个原子操作,这将由CPU本身提供。
Therefore the challenge of developing lock-free algorithms is not the removal of synchronization entirely, it boils down to reduce the critical section of the code to a single atomic operation which will be provided by the CPU itself.
这篇关于x86 CMPXCHG是原子的,如果是这样,为什么它需要LOCK?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!