Skip to content

Race Conditions

Lesson 2 of 15 · 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

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

A lost update happens because both threads: