Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)
Deadlocks in multi-threaded applications:
In Simple Words: Thread A holds Lock 1 and waits for Lock 2, while Thread B holds Lock 2 and waits for Lock 1. Both freeze indefinitely. Prevention: Always acquire multiple locks in identical order across all code paths.
python
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
# Safe: Both threads acquire Lock A first, then Lock B
def worker():
with lock_a:
with lock_b:
print("Acquired both safely!")