Understanding why simple counter increment is not thread-safe
This question probes a fundamental concept in concurrent programming: the gap between high-level source code and low-level machine instructions. A single line like counter++ appears atomic to the programmer, but the CPU executes it as a sequence of distinct operations that can interleave dangerously when multiple threads run in parallel.
Interviewers ask this because thread-safety bugs are subtle and costly in production systems—especially in financial infrastructure where correctness is non-negotiable. Understanding why a naive increment fails teaches you to reason about race conditions, the difference between logical atomicity and hardware atomicity, and why synchronisation primitives exist.
- Read-modify-write cycles and instruction-level visibility
- Memory ordering and cache coherence
- Mutual exclusion and synchronisation mechanisms (locks, atomic operations, barriers)