โ Back to Threads, locks and race conditions
๐๏ธ Threads, locks and race conditions: cheat sheet
๐จ The analogyTwo people updating one whiteboard tally: a single marker pen means only one writes at a time.
๐ The regular explanationThreads run at the same time and share memory, so unprotected read-modify-write sequences can lose updates. Locks make critical sections run one thread at a time; careless locking can deadlock.
- The whiteboard says 5. Ana and Ben both need to add one, and both read 5 at the same moment.
- Each works out 5 + 1 = 6 in their head.
- Both write 6. Two people added one, but the tally only went up by one. An update was lost.
- The rule now is that only whoever holds the single marker pen may touch the tally. Ana grabs it.
- Ben wants the pen too, so he waits his turn.
- Ana reads 5, writes 6, and hands the pen back.
- Now Ben takes the pen, reads 6, and writes 7. Nothing is lost.
- A job needs both markers. Ana grabs the red one first, and at the same time Ben grabs the blue one.
- Ana waits for blue, Ben waits for red. Neither will let go first. They wait forever.
- The fix is a house rule. Always pick up red before blue. Then whoever gets red first finishes, and the other just waits a moment.
๐งฉ Key questions
- Ana and Ben both read 5 and both write 6. What went wrong?
- They looked at the same moment, so one addition was lost. It only happens when they look at the same moment, which makes it maddening to find.
- What does the single marker pen guarantee?
- Only the person holding the pen may touch the tally, so each turn is uninterrupted. Anyone else waits for the pen.
- Ana holds red and wants blue; Ben holds blue and wants red. What's the cure?
- A house rule: everyone picks up red before blue. If everyone takes red first, nobody can hold blue while waiting for red.