Multithreading & Thread Safety Lab (Interactive)
Interleave read-modify-write windows against a shared counter, then fix it with mutex or CAS. A deterministic event simulation of lost updates: widen the stale-read window, compare unsynchronized, locked, and lock-free strategies.
Race Conditions & Lock-Free CAS Simulator
N threads hammer a shared counter with read-modify-write windows. Corrupt it, serialize it, or fix it with hardware Compare-And-Swap.
Thread insecurity = shared state ∧ mutable state. Widen the read→write window or add threads to expose more races; mutexes trade throughput for correctness while CAS stays fast until contention drives retries up.
How It Works Under the Hood
Thread insecurity is shared state combined with mutable state. A read-modify-write that lapses for even a few cycles lets another core’s write get silently clobbered — the balance shows $130 instead of $180. Mutexes serialize correctness at a throughput price, while hardware Compare-And-Swap (LOCK CMPXCHG) validates the snapshot in one indivisible instruction and retries on conflict, never sleeping in the kernel. This is how LMAX’s Disruptor hits millions of orders per second.
Core Architectural Principles
- Lost updates = total increments minus final counter; they grow with the read-to-write window and thread count.
- CAS succeeds only when memory still equals the snapshot; conflicts cost a retry, not a context switch.
- Mutexes guarantee correctness via serialization, trading throughput and adding kernel sleep on contention.
Lead with the golden rule: "races require shared AND mutable state, so immutability or message passing eliminates them structurally." Then show mechanics: explain CAS’s compare-and-swap loop, mention volatile/memory barriers for visibility, and cite AtomicLong counters over coarse global locks in metrics paths.
Locks are simple but serialize parallelism; lock-free CAS is fast yet burns retries under contention and is hard to get provably correct.