transfer(a, b) locks a then b. Two threads run transfer(x, y) and transfer(y, x) at the same time and hang. What is the standard fix?
Show answer
Answer
Always lock the two accounts in a fixed order, such as by account id
Each thread holds one lock and waits for the other: circular wait. A global lock order breaks the cycle. Timeouts turn a deadlock into failures or livelock and still need retry logic. Atomic balances make each update safe but not the pair of updates. Read locks do not allow writes and both threads would still need the write lock.