Deadlocks and lock order
hard 65 minTwo threads, two locks, and a program that waits for ever.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Who holds what, who waits for whom, and where the circle closes.
Operations
The circle
Two opposite moves, each locking its first argument first.
Step 1 of 6
Nobody holds anything
Thread 1 moves 3 bikes from shop 1 to shop 2. Thread 2 moves 1 bike the other way.
Step 1: Nobody holds anything
def move_unsafe(src, dst, n): with src.lock: with dst.lock: src.bikes -= n dst.bikes += n- Watch
- The owner fields
- Result
- Both wait for ever
The same code runs twice. Only the arguments differ.
In the real world
The same deadlocks and lock order doing real jobs. Pick one and step through it.
put() tells its listeners while it holds the lock.
Step 1 of 5
A van arrives
Thread 1 takes the stock lock.
Step 1: A van arrives
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Order from the arguments
criticalTwo callers may name the same two objects in opposite orders.
Wrongwith src.lock: with dst.lock: change()Righta, b = sorted((src, dst), key=lambda s: s.id)with a.lock, b.lock: change()Calling out with the lock
criticalThe listener decides what is locked next, and how long you hold yours.
Wrongwith self._lock: self._n += 1 for f in self._listeners: f(self._n)Rightwith self._lock: self._n += 1 n, fs = self._n, list(self._listeners)for f in fs: f(n)Retry without end
majorA livelock looks like work. The caller never hears anything.
Wrongwhile not try_both(a, b): passRightfor i in range(6): if try_both(a, b): return work() sleep(random.uniform(0, 0.01 * 2 ** i))raise BusyThe first lock stays closed
criticalWhen the second try fails, the first lock is never released.
Wronga.acquire()if not b.acquire(timeout=1): return FalseRighta.acquire()if not b.acquire(timeout=1): a.release() return FalseA public locked method calls another
majorWith a plain lock the thread waits for itself.
Wrongdef add(self, x): with self._lock: self.trim() # locks againRightdef add(self, x): with self._lock: self._trim() # expects the lock
Interview tips
Order
- Unique key that never changes.
- One helper takes all.
- Same object twice: refuse or skip.
Short and silent
- No calls out.
- No sleep, join or query.
- Copy, open, then tell.
Giving up
- Release what you have.
- Random, growing pause.
- A limit, then Busy.
When it hangs
- Two dumps first.
- Who holds, who waits.
- Fix the order, add a rank.