Atomic Compare and Swap

Atomically replace a memory value if it still equals an expected value.

Atomics

Semantics

atomically: if (*addr == expected) { *addr = new; } returning success or the observed value. Split into two families: a single CAS instruction, or a load-reserved/store-conditional pair that the software retries.

Architecture Instructions Expressed as How this architecture does it
x86 one instruction Requires a LOCK prefix to be atomic across cores; the expected value lives in RAX and is overwritten with the observed value on failure.
ARM one instruction FEAT_LSE added single-instruction CAS (with acquire/release variants such as CASAL); before that, AArch64 used the LDXR/STXR retry loop.
RISC-V one instruction Classically a load-reserved/store-conditional retry loop from the A extension; the newer Zacas extension adds a true single-instruction AMOCAS.
PowerISA an idiom Uses the reservation model exclusively: lwarx establishes a reservation, stwcx. succeeds only if it survives, and software retries the loop. There is no single-instruction CAS.