What causes a deadlock between two threads, and what are the standard ways to avoid it?
Answer
A classic deadlock happens when thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1 at the same time; neither can proceed and both wait forever. The standard prevention strategies are: always acquire multiple locks in the same globally agreed order across all code paths, use a timeout on lock acquisition (`lock.acquire(timeout=5)`) so a stuck thread eventually gives up and can recover or report an error, or restructure the code to avoid needing to hold more than one lock at a time in the first place.
Strong answer includes
- two threads each hold one lock and wait on the other's lock, forever
- prevention: consistent global lock ordering across all code paths
- alternatives: acquisition timeouts, or avoid holding multiple locks at once
Practical example
transfer(account_a, account_b)locking `account_a` then `account_b` , while a concurrent
transfer(account_b, account_a)locks `account_b` then `account_a` , can deadlock; always locking accounts in a fixed order (e.g. by account id) avoids it.