LOCKS, ATOMICS, LOCK-FREE
Three ways to make one update safe, three different costs
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.
// 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// Atomic read-modify-write: one instruction, the hardware serialises it.
atomic_fetch_add(&counter, 1);
// CAS loop: lock-free. A thread that is descheduled holds nothing;
// a failed CAS means another thread succeeded, so retry.
int old;
do { old = counter; } while (!cas(&counter, old, old + 1)); 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.
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
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.
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.
“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.