AlgoViz

Deadlocks and lock order

hard 65 min

Two threads, two locks, and a program that waits for ever.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 5:12

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 1move(1, 2, 3)holdsnothingthread 2move(2, 1, 1)holdsnothingshop 1Shopownerfreebikes10shop 2Shopownerfreebikes10

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 1in put()holdsstock lockthread 2workerstateidlestockStocklockT1listenerReportput(4)

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

    critical

    Two callers may name the same two objects in opposite orders.

    Wrong
    with src.lock:    with dst.lock:        change()
    Right
    a, b = sorted((src, dst), key=lambda s: s.id)with a.lock, b.lock:    change()
  • Calling out with the lock

    critical

    The listener decides what is locked next, and how long you hold yours.

    Wrong
    with self._lock:    self._n += 1    for f in self._listeners: f(self._n)
    Right
    with self._lock:    self._n += 1    n, fs = self._n, list(self._listeners)for f in fs: f(n)
  • Retry without end

    major

    A livelock looks like work. The caller never hears anything.

    Wrong
    while not try_both(a, b):    pass
    Right
    for i in range(6):    if try_both(a, b): return work()    sleep(random.uniform(0, 0.01 * 2 ** i))raise Busy
  • The first lock stays closed

    critical

    When the second try fails, the first lock is never released.

    Wrong
    a.acquire()if not b.acquire(timeout=1):    return False
    Right
    a.acquire()if not b.acquire(timeout=1):    a.release()    return False
  • A public locked method calls another

    major

    With a plain lock the thread waits for itself.

    Wrong
    def add(self, x):    with self._lock:        self.trim()      # locks again
    Right
    def 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.