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 等缓存连贯性协议，而不需要锁住总线了。