Race Conditions
Concurrency: lesson 2 of 10
Two readers, one write survives.
Lesson 2 of 10 · 5 min
Race Conditions
Step 1 of 12
One counter, two threads, each running count += 1. The schedule decides the answer.
The Idea
A race condition is when the answer depends on who got there first. Two threads read the same value, both add one to their own copy, and both write back. One increment silently disappears — no error, no crash, just a number that is quietly wrong.
Real-World Example
A climbing gym tracks harnesses on a whiteboard. Two staff each glance at "12 out", each issue a harness, and each write 13. Fourteen harnesses are on the wall and the board insists there are thirteen. Nobody did anything wrong on their own.
The Code
# one shared counter, two workers, a fixed interleaving
shared = {"count": 0}
steps = [("A", "read"), ("B", "read"), ("A", "write"), ("B", "write")]
local = {}
for who, action in steps:
if action == "read":
local[who] = shared["count"] # both workers see 0
else:
local[who] += 1
shared["count"] = local[who] # the later write erases the earlier
print(shared["count"]) # 1 — two increments, one survivor
Your turn
What does this print?
shared = {"count": 0}
steps = [("A", "read"), ("A", "write"), ("B", "read"), ("B", "write")]
local = {}
for who, action in steps:
if action == "read":
local[who] = shared["count"]
else:
local[who] += 1
shared["count"] = local[who]
print(shared["count"])Mini quiz
1 / 3