CMPXCHG
CPU instruction that atomically compares a memory value with a register and conditionally swaps them.
Compare-and-exchange. CMPXCHG is the x86 instruction that implements atomic compare-and-swap at the hardware level. It reads a value from a memory address, compares it to a register, and conditionally writes a new value back—all as a single locked operation that no other CPU can interleave. If the comparison fails, the register is updated with the actual memory value and status flags are set accordingly.
CMPXCHG is the foundation of lock-free algorithms: a thread can repeatedly invoke it in a loop until it succeeds. Without hardware atomicity, hundreds of threads could read the same value, compute the next step, and write back simultaneously—most would clobber each other's work. With CMPXCHG, only one succeeds; the rest learn they failed and retry.