How Race Conditions Happen
Two threads, one variable, and a bug that only shows up sometimes.
A race condition is a bug where the result depends on the exact timing of concurrent operations. It hides in the gap between reading a value and writing it back.
Legend — how to read this diagram
The classic lost update
- Both read. Thread A and Thread B both read
count = 5. - Both compute. Each independently decides the new value is 6.
- Both write. They both store 6 — but two increments happened, so it should be 7.
- Non-determinism. Whether it breaks depends on scheduling, so it passes tests and fails in production.
How to prevent them
Locks. A mutex makes read-modify-write atomic, one thread at a time.
Atomics. Hardware atomic operations do increment as a single indivisible step.
Avoid shared state. Message passing and immutability sidestep the problem entirely.
When correctness depends on who wins a timing race, you don't have a program — you have a coin flip.
No comments:
Post a Comment