Advertisement
Without atomic increment, concurrent threads lose updates. Expected vs actual diverges.
What you're seeing
counter++ is actually three operations: load, increment, store. Two threads can read
the same value, both increment, both store — losing one update.
Real CPUs reorder reads/writes; the bug is worse than the simple model suggests. Atomic ops (CAS, atomic increment) preserve the happens-before relationship. Locks work but are slower.
★ KEY TAKEAWAY
counter++ is three ops (load, inc, store). Concurrent threads can lose updates. Atomic ops fix it.
▶ WHAT TO TRY
- Run with atomic off — see lost updates.
- Run with atomic on — perfect count.
- The probability of races grows with thread count.