multithreading - 为什么 CompareAndSwap 指令被认为是昂贵的?

标签 multithreading synchronization multicore

为什么 CompareAndSwap 指令被认为是昂贵的?

我在一本书中读到:

“内存障碍很昂贵,大约
昂贵的原子 compareAndSet()
操作说明。”

谢谢!

最佳答案

“CAS 与普通存储没有明显不同。关于 CAS 的一些错误信息可能来自于英特尔处理器上 lock:cmpxchg (CAS) 的原始实现。lock: 前缀导致 LOCK# 信号被断言,获得独占"-大卫骰子,Biased locking in HotSpot

"Memory barriers are expensive, about as expensive as an atomic compareAndSet() instruction."



这是完全正确的。
例如。在 x86 上,多处理器系统上的正确 CAS 具有锁定前缀。
锁定前缀会导致完整的内存屏障:

"...locked operations serialize all outstanding load and store operations (that is, wait for them to complete)." ..."Locked operations are atomic with respect to all other memory operations and all externally visible events. Only instruction fetch and page table accesses can pass locked instructions. Locked instructions can be used to synchronize data written by one processor and read by another processor." - Intel® 64 and IA-32 Architectures Software Developer’s Manual, Chapter 8.1.2.



内存屏障实际上是​​作为虚拟 LOCK OR 实现的。或 LOCK AND在这两个 the .NETthe JAVA JIT在 x86/x64 上。
在 x86 上,CAS 会导致完整的内存屏障。

在 PPC 上,情况有所不同。一个 LL/SC对 - lwarx & stwcx - 可用于将内存操作数加载到寄存器中,然后如果没有其他存储到目标位置,则将其写回,或者如果有,则重试整个循环。可以中断 LL/SC。
这也不意味着自动全围栏。
在不同的架构上,性能特征和行为可能会有很大差异。
但话又说回来 - 一个 weak LL/SC不是CAS。

关于multithreading - 为什么 CompareAndSwap 指令被认为是昂贵的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2972389/

相关文章:

C++11线程等待

OpenGL:为计算着色器使用多个全局工作组有好处吗

java - 有什么方法可以中断、终止或以其他方式解除(释放同步锁)单个死锁的 Java 线程,从而允许其他线程继续执行?

c# - 在哪里可以找到 Paint.NET 多线程白皮书?

arm - 中断如何在多核 ARM cpu 上工作

c - 微基准测试显示进程切换比线程切换更快;怎么了?

ruby - 介绍性 Ruby 线程问题

java - 使用 TextArea.append() 时出现 NullPointerException

Javascript函数执行同步

node.js - 如何设计分布式 node.js Web 服务器