01 · Why it’s true
Something as simple as count = count + 1 is really three steps: read the value, add one, write it back. When two threads run those steps at the same time, they can both read the same old value, and one update is lost.
Whether it happens depends on timing, so the bug can pass every test and appear only under load. The fix is to make the read-modify-write atomic: a lock (mutex), an atomic operation, or giving each piece of data a single owner.
02 · Picture it
03 · In the interview
- Writing thread-safe code in coding rounds (for example, a counter or a cache).
- Debugging intermittent issues that appear only under load.
- Knowing the costs: lock contention, deadlocks, and how to avoid them (always take locks in the same order).
04 · Practice question
“Our request counter shows fewer requests than the load balancer logged. The code is counter += 1 in a multi-threaded server. Why, and how do you fix it?”
A strong answer covers
+=is a read, an add, and a write; two threads can interleave and lose an update.- Fix with an atomic increment, or protect the update with a mutex.
- At high request rates, reduce contention with per-thread counters that are summed when read.
- Add a test that hammers the counter from many threads and checks the total.
Want to play with it? Open the interactive deep dive →