Break one condition: avoid mutual exclusion where possible (read-only or sharable resources), require processes to request all resources at once (no hold and wait, at the cost of utilization), allow preemption (release and retry), or impose a global ordering on resources (no circular wait), which is the most practical.
Other practical tools: lock timeouts or try-lock with backoff, and holding locks for as short a time as possible.
# Deadlock-prone: thread 1 locks A then B, thread 2 locks B then A.
# Fix: always acquire locks in one global order.
def transfer(src, dst, amount):
first, second = sorted((src, dst), key=lambda acct: acct.id)
with first.lock:
with second.lock:
src.balance -= amount
dst.balance += amount