Back
+15 XP
Concept

Deadlocks: The Fatal Lock Ordering Trap

A deadlock happens when Thread 1 holds Lock A and waits for Lock B, while Thread 2 holds Lock B and waits for Lock A. Both freeze forever. Prevent it by enforcing strict lock ordering 💀.

python
import threading

lock_a = threading.Lock()
lock_b = threading.Lock()

# Safe practice: Always acquire locks in the exact same global order!
def safe_routine():
    with lock_a:
        with lock_b:
            print("Both locks acquired safely without deadlock! 🛡️")

safe_routine()

# 60. Deadlocks: The Fatal Lock Ordering Trap A deadlock happens when Thread 1 holds Lock A and waits for Lock B, while Thread 2 holds Lock B and waits for Lock A. Both freeze forever. Prevent it by enforcing strict lock ordering 💀. ```python import threading lock_a = threading.Lock() lock_b = threading.Lock() # Safe practice: Always acquire locks in the exact same global order! def safe_routine(): with lock_a: with lock_b: print("Both locks acquired safely without deadlock! 🛡️") safe_routine() ``` Never acquire locks in opposite order in different functions (`A then B` vs `B then A`). Uniform lock acquisition order is the #1 defense against deadlocks! 💀 --- ### Question What is the most effective architectural strategy to prevent deadlocks when using multiple locks? 🧠 - [ ] a. Enforce a strict, uniform global ordering when acquiring multiple locks 🛡️ - [ ] b. Never use more than 1 MB of memory per thread - [ ] c. Run Python with the -O optimization flag - [ ] d. Increase thread priority in the OS task manager --- ### Challenge Create two locks `l1 = threading.Lock()`, `l2 = threading.Lock()`. Safely acquire `l1` then `l2` using nested `with` blocks and print `'Ordered acquisition'`. 🎯 <details> <summary>Solution</summary> ```python import threading l1 = threading.Lock() l2 = threading.Lock() with l1: with l2: print("Ordered acquisition") ``` </details>

Checkpoint

What is the most effective architectural strategy to prevent deadlocks when using multiple locks? 🧠

Practice

Create two locks `l1 = threading.Lock()`, `l2 = threading.Lock()`. Safely acquire `l1` then `l2` using nested `with` blocks and print `'Ordered acquisition'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks