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)returnsFalse(changing nothing) ifsrc == dst,amount <= 0, orsrchas less thanamount.- Use one lock per account, not a global lock: transfers between unrelated accounts must run at the same time.
- Never deadlock, even with
a → bandb → arunning concurrently. Bank(balances, work=None): if given, callwork()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?