A race condition is a bug where the outcome depends on the timing of two or more threads. When they touch shared data and the order is not controlled, results vary from run to run.
Take two threads each reading a counter, adding one, and writing back. If both read the same value before either writes, one increment is lost. The count is wrong only for certain interleavings.
It is hard to reproduce because the bad interleaving is rare. Scheduling is nondeterministic and shifts with load, timing, and the machine. That is why rerunning does not debug a race. You fix it by reasoning about shared state and adding synchronization, not by hunting for the one crash.
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Can you give a race that is not a counter, such as a check-then-act?Both threads pass the check before either acts, like both seeing a key missing and both inserting. Check and act must become one atomic step.
A race condition is a bug where the result depends on the timing of two or more threads that touch shared data in an order nobody controls.
The classic case is two threads incrementing a counter, where each one reads the value, adds one, and writes it back.
If both read the same value before either one writes, one increment is lost, and that only happens for certain interleavings.
It's hard to reproduce because that bad interleaving is rare, and the scheduler is nondeterministic, so the timing shifts with load and with the machine.
That's why rerunning doesn't debug a race, since a clean run proves nothing, so I reason about the shared state and add synchronization instead.
Weak answers to avoid
Says to rerun it until it failsThe bad interleaving is rare, so a clean run proves nothing. Say you find the shared state and add synchronization instead.
Adds a sleep or a retry as the fixA sleep only shifts the timing, so the race hides instead of going away. Control the order with synchronization.
Defines it without an exampleAbstract talk about timing sounds memorized. Walk the read, add and write, and show where two threads overlap and lose an update.
Says one core means no raceOn one core the scheduler can still switch threads between the read and the write. Races come from interleaving, not true parallelism.
Interview lens
Likely follow-ups, what you can say, and the weak answers to avoid.