0%

CAS

概要

CAS Compare and Swap 学习,看到网上到处有人说 CAS 是一种无锁算法,实在是有点忍不住,这种对于技术的研究,需要一种寻根究底的态度,模棱两可没掌握清楚,就随便发帖,然后后面的人也是人云亦云,这样整体的技术水平怎么可能得到提高呢?

博客

IT老兵博客

正文

参考维基

In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of that memory location to a new given value. This is done as a single atomic operation. The atomicity guarantees that the new value is calculated based on up-to-date information; if the value had been updated by another thread in the meantime, the write would fail. The result of the operation must indicate whether it performed the substitution; this can be done either with a simple boolean response (this variant is often called compare-and-set), or by returning the value read from the memory location (not the value written to it).

CAS 其实是一个原子指令,而多线程的同步、无锁算法的实现是要基于它来完成的,它完成的工作是比较并且交换,比较,如果相同的话,则赋值;否则,不赋值,可能是通过一个 boolean 值来返回。

参考这里

The most famous rumor about the CAS instruction is that CAS needs to lock the bus, so the CAS instruction is not only slow but also seriously affects the system concurrency, even if there is no conflict. But in newer CPUs (after 486 for Intel CPUs), this is not the case. The current CPU generally adopts a good cache coherence protocol, which can prevent the occurrence of a lock bus in many cases. The most famous of these is the MESI cache coherence protocol used in Intel CPUs.

早期的实现,是要锁住总线的,但是在 486 之后,采用了例如 MESI 等缓存连贯性协议,而不需要锁住总线了。

总结

计算机科学与技术,这是一门工科学业,而工科是需要大量地理论学习和认真地实践,务实地去研究和做事的。

参考

https://en.wikipedia.org/wiki/Compare-and-swap
https://titanwolf.org/Network/Articles/Article?AID=8cac1f8e-6ddd-4252-8797-c6a17aa304ec#gsc.tab=0