0 day streak
6. ConcurrencyAtomics and CAS

Atomics and CAS

Atomics are operations the CPU guarantees happen all at once, so no other thread can see them half done or slip in between their steps. The most important is compare-and-swap, or CAS: “if this memory still holds the value I expect, replace it with my new one, otherwise tell me it changed.” With CAS you can update shared data without a lock: read the current value, compute a new one, and retry if someone else got there first. That’s the foundation of lock-free queues, counters and reference counts. The catch is subtle bugs like the ABA problem, where a value changes and then changes back, so a CAS succeeds even though the state underneath moved on.

In this lesson: Step through CAS. The ABA problem as a playable scenario.