◄ Wiki / OS
compare-and-swap (CAS)
An atomic operation that updates a value only if it still equals what you expected, all in one indivisible step.
CAS is the fundamental building block of lock-free and locking code: it reads a memory location, checks it against an expected value, and writes a new value only on a match — with no chance of another thread interfering mid-operation. Nearly every lock is built on top of it. If the implementation writes back the wrong operand (say the expected value instead of the desired one), every lock built on it silently breaks.
See also
- CMPXCHGThe x86 CPU instruction that atomically compares a value in memory and swaps in a new one only if it matched.
- critical sectionA stretch of code that must be run by only one thread at a time to avoid corruption.