Why count++ Is Not Atomic
You'll learn: Why the innocent-looking count++ operation can produce incorrect results in multi-threaded programs.
When you write count++, it looks like a single operation — but the CPU doesn't see it that way. Under the hood, this simple increment actually involves three distinct steps:
- Read the current value of
countfrom memory - Modify that value by adding 1
- Write the new value back to memory
These steps are called read-modify-write, and they are not atomic — meaning another thread can interrupt between any of these steps.
The Interleaving Problem
Imagine two threads both trying to increment count from 0 to 2. Here's what can go wrong:
Thread A reads count (sees 0)
Thread B reads count (sees 0)
Thread A adds 1 (calculates 1)
Thread B adds 1 (calculates 1)
Thread A writes 1 back to count
Thread B writes 1 back to count
Final result: count = 1 (should be 2!)
Both threads read the same initial value before either one writes back. The second write overwrites the first, losing an increment entirely.
The Analogy
Think of count++ like updating a shared whiteboard. You walk up, read the number (5), turn around to calculate 5+1 in your head, then write 6. But while your back was turned, someone else read 5, calculated 6, and wrote it — so when you write your 6, you've both done work but only one increment sticks.
Key Takeaway: count++ involves three separate steps (read-modify-write) that can be interleaved across threads, causing lost updates and race conditions — that's why it's not thread-safe without synchronization.