What is Compare-and-swap?

An atomic instruction that writes a new value only if memory still holds an expected value. Wrapped in a retry loop, it enables lock-free updates.

Field: Multicore & Synchronization

Japanese name: コンペア・アンド・スワップ

What CAS guarantees

CAS (compare-and-swap) takes an address, an expected value and a new value. In one indivisible step it reads the location, compares it with the expected value and, only if they match, stores the new value; it reports success or failure, often by returning the value it found. On x86 this is the lock cmpxchg instruction. C11 exposes it as atomic_compare_exchange_strong and _weak, and C++ as compare_exchange_strong and compare_exchange_weak on std::atomic. In hardware, the core obtains the cache line in an exclusive state so no other core can write it during the operation.

The retry loop

A lock-free update reads the current value, computes the new value from it and attempts a CAS with the value read as the expected value. If another thread changed the location in the meantime, the CAS fails and the loop rereads and tries again. Some thread always succeeds, so the system as a whole makes progress without locks, which makes such code lock-free but not wait-free: one unlucky thread can retry indefinitely. Under heavy contention many retries and the cache line bouncing between cores can make a CAS loop slower than a simple lock.

The ABA problem

CAS checks only that the value is equal, not that it was never changed. If a location changes from A to B and back to A between a thread's read and its CAS, the CAS succeeds even though the data structure may now be different. The classic case is a lock-free stack where a node is popped, freed and reallocated at the same address before another thread's pop completes. Common remedies are pairing the pointer with a version counter updated on every change, and safe memory reclamation schemes such as hazard pointers or epoch-based reclamation.

CAS vs. LL/SC and fetch-and-add

Many RISC architectures provide load-linked/store-conditional (LL/SC) instead: in RISC-V, lr reserves an address and sc stores only if no other write to it has occurred since, failing otherwise. Because it detects any intervening write rather than comparing values, it avoids ABA in principle, but the reservation can be lost for unrelated reasons, which is why compare_exchange_weak is allowed to fail spuriously. For simple operations such as counters, atomic fetch-and-add, or RISC-V AMO instructions like amoadd, is better than a CAS loop because it never needs to retry.

Try it: questions about Compare-and-swap

What does the atomic CAS (compare-and-swap) instruction do?

  1. AIt writes a new value only if memory equals an expected value, and reports whether it succeeded
  2. BIt compares two memory values and writes the larger into both
  3. CIt swaps a memory value and a register value unconditionally
Show answer and explanation

Answer: A. It writes a new value only if memory equals an expected value, and reports whether it succeeded

CAS atomically performs "if the value at this address is still the expected value, change it to the new value". If another thread changed the value between the read and the write so that it no longer equals the expected value, it fails. Only the value is compared, so a value that changed and then returned still succeeds (the ABA problem). Wrapping it in a loop that rereads, recomputes and retries on failure lets shared values be updated safely without a lock. x86's cmpxchg instruction with the lock prefix is an example.

FAQ

What is the ABA problem in compare-and-swap?

A CAS succeeds because the location holds the expected value again, even though it was changed to something else and back in between. This can corrupt lock-free structures that reuse memory, and is usually prevented with version counters or safe memory reclamation.

Is a CAS loop lock-free or wait-free?

Lock-free. Apart from spurious failures of weak forms, a CAS fails only because another thread's update succeeded, so the system progresses, but an individual thread has no bound on how many retries it may need.

What is the difference between compare_exchange_weak and compare_exchange_strong?

The weak form may fail even when the value matches, which lets it map directly to LL/SC instructions and suits retry loops. The strong form fails only on a real mismatch, at the cost of an internal loop on LL/SC machines.

Questions that mention Compare-and-swap (1)

Compare-and-swap appears in 2 practice questions across 1 topic, including Multicore & Synchronization.

  1. Which describes an atomic instruction?

Books on Multicore & Synchronization Ad

As an Amazon Associate I earn from qualifying purchases.

This page was drafted with AI and fact-checked by a separate AI review before publication. Our Editorial policy explains how we write and check content. If you spot an error, please tell us on our Contact page.

Back to the glossary