Correctness: races on shared state
hard 75 minWhen several threads use the same data, their steps mix, and a rule that each of them respects can still break.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Cut the steps, see the damage, close the gap
Operations
The lost update
One line, three steps.
Step 1 of 5
Seven loans
Two windows record one loan each.
Step 1: Seven loans
old = self.loansnew = old + 1self.loans = new- Protects
- Nothing
- Costs
- Lost work
`x += 1` is these three lines.
In the real world
The same correctness: races on shared state doing real jobs. Pick one and step through it.
Visibility between two threads.
Step 1 of 4
A loop
The lamp thread blinks until closing is true. It may keep its own copy of the flag.
Step 1: A loop
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Lock after the check
criticalThe answer is old when the lock is taken.
Wrongif item in free: with lock: free.discard(item)Rightwith lock: if item in free: free.discard(item)Readers without the lock
criticalThey see half a change.
Wrongreturn len(free) + len(loans)Rightwith lock: return len(free) + len(loans)A lock for each caller
criticalDifferent locks do not exclude each other.
Wrongclass Window: lock = new one eachRightclass Desk: one private lockThe inner list leaves
majorOutside nobody holds the lock.
Wrongreturn self._loansRightreturn tuple(self._loans)Network inside
majorOne slow answer stops everybody.
Wrongwith lock: bank.charge(...)Rightreserve; charge; confirmTwo atomics for one rule
majorThere is a moment between them.
Wrongfree.dec(); lent.inc()Rightlent = total - free
Interview tips
Rule first
- Say it as a sentence
- List its fields
- All of them, one guard
Avoid
- Confine it
- Freeze it
- Hand it over
Lock well
- Same lock, whole step
- Check all, then change
- Nothing slow inside
Prove
- Field by field
- All orders of small steps
- Stress comes last