◄ Wiki / OS
CMPXCHG
The x86 CPU instruction that atomically compares a value in memory and swaps in a new one only if it matched.
CMPXCHG is the hardware compare-and-exchange instruction that makes lock-free coordination possible: in one uninterruptible step it checks whether memory holds an expected value and, if so, writes a new value. Its operand semantics are fiddly — the expected value lives in a specific register (EAX) and gets overwritten on failure — and mishandling which register holds what is exactly the kind of subtlety that caused a spinlock bug.
See also
- compare-and-swap (CAS)An atomic operation that updates a value only if it still equals what you expected, all in one indivisible step.
- critical sectionA stretch of code that must be run by only one thread at a time to avoid corruption.
- coreOne independent execution unit inside a CPU that can run a thread on its own.