Expert · Module 25 · Lesson 2 of 5
Atomics and compare-and-swap
Atomic loads, stores and read-modify-write operations let two threads update one value without a lock. This lesson traces a CAS loop whose swap fails and retries, and picks the weakest memory ordering that is still correct.
By the end you can
- Explain what an atomic read-modify-write guarantees that a separate load and store cannot
- Write a CAS loop and trace an attempt that fails on a mismatched expected value
- Choose relaxed, acquire-release or sequential consistency for a shared update
Builds on Data races and locks, Amortized analysis.
01 · A question first
Compare-and-swap is one instruction with no lock in it, and a loop built on it keeps every update. The interesting part is what happens when the swap fails: nothing is corrupted, nobody waits, and the attempt starts over. What does a failed CAS prove about the world?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- What an atomic operation adds
- Compare-and-swap, then the loop
- Why the loop needs no lock
- fetch_add and test-and-set
- Memory ordering in practice
- Where atomics show up
- Pseudocode & Multi-Language Implementations (C++, Java, Python)
- Complexity Derivation, Edge Cases & Common Mistakes
03 · Practice
Something wrong with this lesson? Report a problem