OS, networking and concurrency · Question 33 of 50
What is a race condition? Give an example and a fix.
Spotting check-then-act, and making it atomic.
The answer
The result depends on the timing of operations that overlap. The classic: two requests read a balance of ₹1,000 at the same moment, both check that ₹800 is affordable, and both withdraw. The same happens with in-memory counters across threads, and with "check that the username is free, then insert".
Make the check and the change one atomic step (a conditional UPDATE, a unique constraint, Redis INCR), or lock (a mutex, SELECT ... FOR UPDATE), or use optimistic versions and retry. In Node, races happen between awaits, not inside synchronous code.
-- the race: SELECT the balance, check it in code, then UPDATE
-- atomic:
UPDATE accounts SET balance = balance - 800
WHERE id = 1 AND balance >= 800; -- 0 rows: not enough moneyThe picture
t1: read 1000 ── check OK ───────────────── write 200 t2: read 1000 ── check OK ── write 200 two withdrawals, one check fix: one atomic "UPDATE ... WHERE balance >= 800"
Can single-threaded JavaScript have races?
Show the answer
Yes, between awaits: two async handlers both read the state, both await something, then both write.