atomic - 为什么 CAS(原子)操作比同步或 volatile 操作更快

标签 atomic compare-and-swap

据我了解,synchronized关键字将本地线程缓存与主内存同步。 volatile 关键字基本上总是在每次访问时从主内存中读取变量。当然,访问主内存比本地线程缓存要昂贵得多,因此这些操作的成本很高。然而,CAS 操作使用低级硬件操作,但仍然必须访问主存储器。那么 CAS 操作如何更快呢?

最佳答案

我认为关键因素正如您所说 - CAS 机制使用低级硬件指令,可以实现最少的缓存刷新和争用解决。

其他两种机制(同步 volatile )使用不同的架构技巧,这些技巧在所有不同的架构中更普遍可用。

在大多数现代架构中,CAS 指令都以一种或另一种形式提供,但每种架构中都会有不同的实现。

来自 Brian Goetz 的有趣引用(据说)

The relative speed of the operations is largely a non-issue. What is relevant is the difference in scalability between lock-based and non-blocking algorithms. And if you're running on a 1 or 2 core system, stop thinking about such things.

Non-blocking algorithms generally scale better because they have shorter "critical sections" than lock-based algorithms.

关于atomic - 为什么 CAS(原子)操作比同步或 volatile 操作更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623026/

相关文章:

rest - 使用 REST 避免重复的 POST

object - C++11 只能将原始数据类型声明为原子的吗?

multithreading - SetEvent是原子的吗?

algorithm - 比较并交换符合 POSIX 标准的文件系统对象

c - 普通C库中有TestAndSet(volatile int *lock)函数吗?

c - C 和 gcc 中原子变量的相等性测试

c++ - 什么在 CUDA : global memory write + __threadfence() or atomicExch() to global memory? 中更快

c - 如何在c中使用 'cmpxchg8b'汇编指令实现原子比较和交换?

multithreading - 没有LOCK前缀的CMPXCHG指令的目的?

c++ - 在 C++ 中将指针转换为 volatile void**