Demonstrating Race Conditions with Shared Counters
What you'll learn: How multiple threads incrementing a shared counter can produce incorrect results due to race conditions.
The Classic Counter Problem
Imagine two bank tellers (threads) both trying to update the same account balance display at exactly the same time. Each reads the current value, adds their transaction, and writes it back. But if they both read before either writes, one transaction gets lost!
This is exactly what happens with a shared counter—a variable that multiple threads try to increment simultaneously.
How the Race Occurs
Consider a simple operation: counter = counter + 1
This innocent-looking statement actually involves three separate steps:
- Read the current value of
counterfrom memory - Add 1 to that value
- Write the new value back to memory
When two threads execute this "simultaneously," their operations can interleave:
- Thread A reads counter (value: 0)
- Thread B reads counter (value: 0)
- Thread A adds 1 (result: 1)
- Thread B adds 1 (result: 1)
- Thread A writes 1
- Thread B writes 1
Expected result: 2
Actual result: 1
One increment was lost!
Why This Matters
If you launch 1000 threads that each increment a counter 1000 times, you'd expect the final value to be 1,000,000. But due to race conditions, you might get 437,892 or 823,445—unpredictable and wrong every time you run it.
This demonstrates why unsynchronized access to shared data is dangerous—the results depend on precise timing, which you can't control.
Key Takeaway: A shared counter incremented by multiple threads without synchronization is a simple but powerful demonstration of how race conditions cause data corruption through interleaved read-modify-write operations.