为什么CAS(原子)操作比同步或易失性操作快 [英] Why are CAS (Atomic) operations faster than synchronized or volatile operations

查看:228
本文介绍了为什么CAS(原子)操作比同步或易失性操作快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

我相信关键因素就在您所说的-CAS机制使用低级硬件指令,这些指令可实现最小的缓存刷新和争用解决.

其他两种机制(synchronizationvolatile)使用不同的体系结构技巧,这些技巧在所有不同的体系结构中更常见.

CAS指令在大多数现代体系结构中都可以以一种或另一种形式使用,但是每种体系结构中都有不同的实现方式.

来自 Brian Goetz (据说)的有趣报价

操作的相对速度在很大程度上不是问题.相关的是基于锁的算法和非阻塞算法之间在可伸缩性方面的差异.而且,如果您在1或2核心系统上运行,请不要考虑这些事情.

非阻塞算法通常具有更好的伸缩性,因为它们具有较短的临界区".比基于锁的算法要好.

From what I understand, synchronized keyword syncs local thread cache with main memory. volatile keyword basically always reads the variable from the main memory at every access. Of course accessing main memory is much more expensive than local thread cache so these operations are expensive. However, a CAS operation use low level hardware operations but still has to access main memory. So how is a CAS operation any faster?

解决方案

I believe the critical factor is as you state - the CAS mechanisms use low-level hardware instructions that allow for the minimal cache flushing and contention resolution.

The other two mechanisms (synchronization and volatile) use different architectural tricks that are more generally available across all different architectures.

CAS instructions are available in one form or another in most modern architectures but there will be a different implementation in each architecture.

Interesting quote from Brian Goetz (supposedly)

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.

这篇关于为什么CAS(原子)操作比同步或易失性操作快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆