progress

~/problems / Locks / Deadlock and lock ordering

Take several locks without deadlock

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Implement run_with_locks(locks, fn): acquire all the threading.Locks in locks, call fn() while holding them, release them all, and return fn()'s result.

  • Many threads call it at once with overlapping locks listed in different orders. It must never deadlock.
  • If fn() raises, release every lock and let the exception propagate.
  • A lock may appear more than once; acquire it only once. An empty list just calls fn().
a, b = threading.Lock(), threading.Lock()
# thread 1: run_with_locks([a, b], transfer)
# thread 2: run_with_locks([b, a], transfer)
# Taking them in the order given: 1 holds a and waits for b, 2 holds b and waits for a -> stuck forever.
run_with_locks([a, a], lambda: 7)   # 7

Up to 10 locks per call. Don't sleep, busy-wait or use one global lock for everything.

Show hint

a deadlock needs a cycle of waiting. Break it by taking the locks in one order every thread agrees on, such as sorted(set(locks), key=id).

Topic: Deadlock and lock ordering. The four conditions and how to break one.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc