Beginner Topic 13 of 51 Concurrency & Parallelism
Compare-and-Swap
Primitive updating a value only if unchanged.
How it works
Compare-and-swap is an atomic instruction that takes a memory location, an expected value and a new value: if the location holds the expected value, it is replaced with the new value and the operation reports success; otherwise nothing changes and it reports failure. Retrying in a loop gives lock-free updates: read the current value, compute the new one and CAS, retrying if another thread changed it in between. Hardware provides it as CMPXCHG on x86 and load-linked and store-conditional on ARM and RISC-V.
Where it is used
Lock-free stacks and queues, atomic counters, spin locks, reference counting and optimistic concurrency in databases use CAS.
Common pitfall
The ABA problem, where a value changes from A to B and back to A so CAS succeeds incorrectly, needs tagged pointers or hazard pointers. Under contention, retry loops waste CPU and may starve. Memory reclamation is hard in lock-free structures. Only operates on word-sized values unless double-width CAS exists. Use well-tested libraries before hand-rolling.
Where it fits in the course
Compare-and-Swap is topic 13 of 51 in Concurrency & Parallelism, rated Beginner. It follows Atomic Operations. The next topic is Memory Barriers.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Concurrency & Parallelism quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Concurrency & Parallelism quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Compare-and-Swap?
Where do people use Compare-and-Swap?
What is the most common mistake with Compare-and-Swap?
What should I learn before this topic?
How can I practice it?
Is Compare-and-Swap hard to learn?
How long does it take to learn Compare-and-Swap?
Which topics are related to Compare-and-Swap?
What should I study after Compare-and-Swap?
Related topics
- Atomic Operations (Concurrency & Parallelism)
- Memory Barriers (Concurrency & Parallelism)
- Producer-Consumer Pattern (Concurrency & Parallelism)
- Volatile and Visibility (Concurrency & Parallelism)