Definition
Compare-and-swap (CAS) is an atomic read-modify-write operation, a single step that no other thread (instruction sequence sharing the same memory) can split. It takes a memory location, an expected value and a new value. If the location holds the expected value, CAS writes the new value; otherwise it writes nothing. Either way it reports whether it succeeded, and usually the value it found. A thread uses CAS to install an update only if the location still holds the value the update was computed from. C calls the operation compare-and-exchange.
The idea
A thread wants to add 1 to a shared counter without a lock. It reads 3 and computes 4. Before it writes, another thread may have changed the counter, and writing 4 would then destroy that thread’s update. The thread needs to say: write 4, but only if the counter still holds 3. CAS is that conditional write, performed as one indivisible step, so that no other write can slip between the comparison and the replacement.
With CAS, any update computed from one word becomes an optimistic loop: read the value, compute the new value privately, and try to install it with CAS. If the CAS fails, read the word again and recompute. The picture is a shared document that accepts a save only if it is still the version the editor opened. The picture stops at one point: CAS compares contents, not history. A document that was changed and then changed back looks unchanged to it.
How it works
Let be the shared location, the expected value and the desired new value. One performs, as a single atomic step:
read the current value of ;
if , write to and report success;
otherwise leave unchanged and report failure, together with .
The usual retry loop applies an update , such as adding 1:
Load the current value of into .
Compute .
Run . On success, stop: was applied to the value that held at that instant.
On failure, set to the value the CAS found and go back to step 2. Never retry the old : it was computed from a value that is no longer current.
Processors provide CAS directly or build it. x86 processors have lock cmpxchg, and Arm processors of the Armv8.1-A architecture and later have a CAS instruction. Processors with load-linked/store-conditional (LL/SC) instructions instead, such as LDREX and STREX on Armv7-M, load the word and set a reservation, a hardware mark on its address, then compare in software, and store only if no other write has reached the word since the load. In C11, the 2011 edition of the C standard, atomic_compare_exchange_strong(obj, &expected, desired) returns true on success. On failure it returns false and copies the value it found into expected, which is exactly step 4 of the loop. The standard describes the comparison as a comparison of bytes, as if by memcmp, not by the == operator of the type.
C11 also offers atomic_compare_exchange_weak, which may fail spuriously: it may report failure although the location held the expected value. On LL/SC processors the reservation can be lost for reasons unrelated to the value, such as an interrupt §6.11, and the weak form lets the compiler omit an inner retry loop. Code that already loops should use the weak form. The _explicit versions take two memory orders, one for success and one for failure. The failure order may not be release or acquire-release, because a failed CAS writes nothing.
A retry loop built on the strong form is lock-free §9.13: some thread always completes its update. A thread’s CAS fails only because changed after the thread read it, which means another write, usually another thread’s successful update, came in between. The loop is not wait-free, the stronger property that every thread completes within a bounded number of its own steps: nothing bounds how often one particular thread loses. Callers therefore need a policy for repeated failure, such as waiting for a growing delay between attempts (backoff), bounding the number of attempts, or falling back to a lock.
Worked example
A shared counter holds 3, and threads A and B each want to add 1.
A loads 3 and computes .
B loads 3, computes 4 and runs . The counter holds 3, which equals the expected 3, so B succeeds: .
A runs . The counter holds 4, and , so A fails and receives the current value 4.
A recomputes and runs . The counter holds 4, so A succeeds: .
Both increments count, and A did one extra round of work. Had A updated to 4 but retried its old , would have succeeded and left the counter at 4, losing one of the two increments.
A changed generation fools CAS. A lock-free stack keeps a pointer top to its first node. A pop reads top, reads that node’s next pointer, and runs . The stack holds nodes at addresses A, B and C, in that order from the top.
Thread 1 starts a pop: it reads and , and is then delayed.
Thread 2 pops A, pops B and frees both nodes. It then pushes a new node, and the memory allocator happens to return the freed address A for it. The stack is now A, C, and node B no longer exists.
Thread 1 runs .
topholds A, which equals the expected A, so the CAS succeeds and setstopto B, the address of freed memory.
The value A came back, but it now names a new node: a new generation of the memory at that address. This is the ABA problem §9.25, named after the sequence of values A, then something else, then A again; CAS cannot tell the second A from the first.
The repair stores a generation counter next to the pointer and compares both in one CAS. Write top as the pair (pointer, generation), and let every successful update add 1 to the generation. Start from . Thread 1 reads . Thread 2’s three updates leave , then , then . Thread 1’s compares with , finds them different, and fails, and thread 1 retries from . The pair must fit one atomic operation §9.8: for example a 32-bit node index and a 32-bit generation in one 64-bit word, or a double-width CAS such as cmpxchg16b on x86-64 processors.
Stated precisely
Write for compare-and-swap on location with expected value and desired value . As one atomic step it does Here compares the bytes of the two values. The weak form may also return failure when . Atomic means that in the modification order of , the single order of all writes to , the write of a successful CAS comes immediately after the value it compared: no write by any thread falls between the comparison and the replacement.
Success proves exactly one thing: at that instant, held bytes equal to . It does not prove that stayed unchanged since the caller read , because may have been changed and changed back. If a generation counter of bits is part of the compared value and every update adds 1 to it, a false success needs the number of updates between the caller’s read and its CAS to be a nonzero multiple of .
Progress: when came from reading , a failure of the strong form means , so some write to happened after that read. If every write to is a successful update by the same loop, each failure implies another thread’s success, which makes the loop lock-free. No bound exists on the number of failures of one particular thread, so the loop is not wait-free.
Limits and common mistakes
CAS covers one location. An invariant that ties two locations together, such as a count that must match a list, needs both values in one word, a double-width CAS on adjacent words, a lock, or a transaction §8.7.
CAS on a pointer protects the pointer, not the object it points to. In the stack example, thread 1 reads A.next through a pointer that another thread may already have freed, which is a use-after-free §4.6 even if the later CAS fails. A memory reclamation scheme must ensure that no node is freed while a thread may still read it: hazard pointers, in which each thread announces the pointers it is reading; epoch-based reclamation, which frees memory only after every thread has passed a point where it holds no references; read-copy update §9.20 (RCU); or reference counting §9.22. Such a scheme also removes the ABA cases caused by address reuse. Nodes taken from a fixed pool and addressed by index avoid the freed-memory read, but still need the generation counter.
Generation counters are subject to counter wraparound §6.21: a counter that passes its largest value starts again from 0. A 16-bit generation returns to the same value after updates, so a thread delayed for that many updates can still be fooled. Choose a width that cannot wrap within the longest delay a thread can suffer.
C compares values even on processors that implement CAS with LL/SC. The expected value came from an earlier, separate load, so the reservation’s ability to notice an intermediate write does not protect C code from the ABA problem.
The weak form can fail without any interference. Code that treats every failure as proof that another thread intervened, for example to count contention, is wrong with the weak form.
Byte comparison surprises. The floating-point values and are equal under == but differ in their sign bit, so a CAS expecting fails on . Padding bytes inside a structure, which hold no value, take part in the comparison too.
Questions answered
Why must callers handle repeated failure and changed object generations?
Callers must handle repeated failure because a compare-and-swap (CAS) can fail any number of times, and changed generations because a successful CAS proves only that the bytes are equal, not that the object behind them is the same one. CAS is an atomic operation that writes a new value to a memory location only if the location still holds an expected value.
Repeated failure: a CAS fails whenever another thread changed the location after the caller read it, and nothing limits how often that happens to one caller. A CAS loop guarantees that some thread progresses, not that this thread does, and the weak form in C may fail with no change at all. A caller must therefore retry in a loop, recompute its new value from the value the failed CAS returned (retrying the stale new value would overwrite another thread’s update), and decide what to do under sustained contention: back off, bound the number of attempts, or fall back to a lock.
Changed generations: a location can go from A to other values and back to A, for example when the memory of a freed node is reused for a new node at the same address. A CAS that expects A then succeeds although A now names a new generation of the object. This is the ABA problem, and it can corrupt a linked structure. The caller must include a generation counter in the compared value, or use a memory reclamation scheme that never reuses an address while a thread may still hold it.
Related entries: ABA problem (§9.25), Lock-free versus wait-free (§9.13), Reference counting (§9.22), Atomic operation (§9.8), Read-copy update (RCU) (§9.20), Counter wraparound (§6.21). Further reading: [78].