progress

~/problems / Locks / Deadlock and lock ordering

Deadlock-free bank transfers

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

easy ~15 min

Implement a thread-safe Bank:

bank = Bank([100, 50, 0])      # balances of accounts 0, 1, 2
bank.transfer(0, 2, 30)        # True: moved 30 from account 0 to 2
bank.transfer(1, 0, 80)        # False: account 1 only has 50, nothing changes
bank.balance(2)                # 30
  • transfer(src, dst, amount) returns False (changing nothing) if src == dst, amount <= 0, or src has less than amount.
  • Use one lock per account, not a global lock: transfers between unrelated accounts must run at the same time.
  • Never deadlock, even with a → b and b → a running concurrently.
  • Bank(balances, work=None): if given, call work() while holding both locks during a successful transfer (the tests use it to be slow).

Account indices are always valid.

Show hint

a deadlock needs two transfers each holding one lock and waiting for the other's. What if every transfer took its two locks in the same agreed order?

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

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