Race Condition
Medium+14 XPWatch two threads both add 1 to a counter — and a whole update vanish. The bug that locks were invented to stop.
No visualization loaded.
Watch
—
Press Run to begin.
When two threads change the same thing at the same time, the result can come out wrong. Press Run and watch two threads each add 1 to a shared counter — and see one of the additions silently disappear.
▸How can adding 1 twice only add 1?
Because 'add 1' is really three steps: read the value, add one, write it back. If both threads read BEFORE either writes, they both see the old number, both compute the same new number, and the second write just overwrites the first. Two adds, one result.
▸Why is it called a 'race'?
Because the outcome depends on who gets there first and in what order — the threads are 'racing'. Run it a thousand times and it might usually work, then fail once when the timing lines up badly. That randomness is what makes these bugs so nasty to catch.
▸What's the 'shared' part that causes trouble?
The counter — one piece of data that both threads can touch. Race conditions only happen on SHARED things. If each thread had its own private counter, there'd be no conflict. Sharing is powerful but dangerous.
▸How do we fix it?
With a lock (the next topic). A lock makes a thread finish its whole read-add-write before any other thread is allowed to touch the counter — so no one can sneak in with a stale value. One at a time = no lost updates.