Lesson 1 · Unit 02
Race conditions
Read, add, write: three steps that can interleave
What you practise
counter += 1is read, add, write- Interleavings that lose updates
- Check-then-act
- Why it passes a thousand times and fails in production
Try a question from this lesson
Pick one
Two threads each run counter += 1 once, and the counter starts at 0. Which final values are possible?
Hint
What if both threads look at the counter before either has changed it?
Correct answer
1 or 2
Why
The statement is three steps: read, add, write. If both threads read 0 before either writes, both write 1 and an update is lost. If one finishes before the other reads, you get 2.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Three steps, not one
counter += 1 is not one action. The thread reads the value, adds one, and writes the result back.
The operating system can pause a thread between any two of those steps and let another thread run.
If the other thread changes the counter in that gap, the paused thread later overwrites it with a stale answer.
tmp = counter # 1. read
tmp = tmp + 1 # 2. add
counter = tmp # 3. writeConcept
Check, then act
The same bug with an if: a thread checks a condition, then acts on it. Between the two, another thread can change the facts.
The check was true when it ran. It may no longer be true when the action happens.
Read-add-write and check-then-act are the two shapes nearly every race takes.
if stock > 0: # check
stock -= 1 # act: is the check
# still true by now?10 more exercises in the app
- 3× type the answer
- 1× true or false
- 4× multiple choice
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.