LOCKS, ATOMICS, LOCK-FREE

Three ways to make one update safe, three different costs

L215 MINRACE CONDITIONS
PREDICT

Four threads each increment a counter once under a mutex. The OS deschedules the lock holder for a few milliseconds. What happens to the other three?

Three ways to make counter++ safe. A mutex serialises the whole load-add-store; it is correct for anything, but a holder that stops running stops everyone behind it. An atomic fetch_add is one instruction the hardware serialises; nothing to hold, nothing to wait for. A CAS loop reads the old value, tries cas(old, old + 1), and retries when it fails. A failed CAS is not a failure: it means another thread succeeded, so the system as a whole moved. That is the lock-free guarantee, and it holds even when a thread is descheduled mid-loop, because a sleeping thread holds nothing.

▶ SIMULATION
SHARED MEMORY
counter = 0
no threads yet
✓ counter == completed increments✓ no tick where every runnable thread is stuck waiting
SCHEDULE
01[SETUP]setup: each thread does lock(); counter++; unlock()
02[CPU]tick 1: every runnable thread runs one instruction
03[OS]OS: deschedule thread A for PREEMPT ticks (it keeps whatever it holds)
04[CPU]tick 2
05[CPU]tick 3
06[CPU]tick 4
07[CPU]tick 5
08[CPU]tick 6
09[CPU]tick 7
10[CPU]tick 8
11[CPU]tick 9
12[CPU]tick 10
13[CPU]tick 11
14[CPU]tick 12
15[CPU]tick 13
16[CPU]tick 14
17[CPU]tick 15
Start of mutex: convoy scenario. 17 steps.
// Mutex: correct, but a holder that gets descheduled stalls everyone.
lock(&m); counter++; unlock(&m);

// CAS without retry: wrong. A failed CAS means the counter moved.
int old = counter;
cas(&counter, old, old + 1);   // returns false, increment is lost

Watch the second invariant: it goes red in MUTEX: CONVOY for every tick the holder is asleep, and stays green in CAS LOOP even while thread A sleeps between its load and its cas. The first invariant goes red only in CAS WITHOUT RETRY.

TUNE IT NOT YET

Same threads, same preemption, three mechanisms. The OS deschedules thread A. Find settings where the threads it never touched (B, C, …) finish at least 7 ticks later under the mutex than under the CAS loop. Watch which lane the descheduled thread hurts, and who pays for it.

GOAL: non-descheduled threads finish 7+ ticks later in the mutex lane than in the CAS lane

FIX IT NOT YET

Implement a lock-free push onto a shared stack. head is an atomic pointer to the top node. Two threads push with your function, and the grader tries every interleaving of their operations, including each write to node.next. After every step it walks the stack: every node it reaches must have next set, and at the end both pushed nodes must be reachable.

Mental model:

a lock is a promise to come back, and the scheduler does not keep your promises. Anything a thread holds while it can be descheduled becomes everyone else’s wait. An atomic holds nothing. A CAS loop holds nothing and retries; the retry is the price of never blocking. Lock-free does not mean fast, it means nobody waits for a thread that is not running.

IN PRODUCTION

Hot counters and metrics under a mutex, reference counts, free-list and queue heads, sequence-number generators. Symptoms are latency tails that scale with the number of threads, not with the work, and a CPU profile that shows waiting rather than computing. Look at std::atomic, fetch_add, compare_exchange_weak loops, and ask who is holding what while asleep.

IN INTERVIEWS

“Mutex or atomic here, and why?” Say what the update touches: one word, use an atomic; a compound invariant, use a lock. Then define lock-free as a progress guarantee, not a speed claim, and explain why a failed CAS must be retried, never ignored.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: EVENT LOOP STARVATION →