TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

โ† 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.
Two writers, one whiteboardStep 3 of 3
๐Ÿ‘ฉAna5 + 1 = 6๐Ÿ‘จBen5 + 1 = 6๐Ÿ“‹ Whiteboard tally6, should be 7
  1. The whiteboard says 5. Ana and Ben both need to add one, and both read 5 at the same moment.
  2. Each works out 5 + 1 = 6 in their head.
  3. Both write 6. Two people added one, but the tally only went up by one. An update was lost.
One marker penStep 4 of 4
๐Ÿ‘ฉAna๐Ÿ‘จBen๐Ÿ–Š๏ธ The one marker๐Ÿ“‹ Whiteboard tally7
  1. The rule now is that only whoever holds the single marker pen may touch the tally. Ana grabs it.
  2. Ben wants the pen too, so he waits his turn.
  3. Ana reads 5, writes 6, and hands the pen back.
  4. Now Ben takes the pen, reads 6, and writes 7. Nothing is lost.
Each holding what the other needsStep 3 of 3
heldheld๐Ÿ‘ฉAna๐Ÿ‘จBenwaits for A๐Ÿ–๏ธ Red marker๐Ÿ–Š๏ธ Blue marker
  1. A job needs both markers. Ana grabs the red one first, and at the same time Ben grabs the blue one.
  2. Ana waits for blue, Ben waits for red. Neither will let go first. They wait forever.
  3. 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.