Back
+15 XP
Concept

Reentrant Locks: threading.RLock

A standard `Lock` freezes if the same thread attempts to acquire it twice. An `RLock` (Reentrant Lock) allows the owning thread to acquire it multiple times without self-deadlocking 🔄.

python
import threading

rlock = threading.RLock()

def inner():
    with rlock:
        print("Inner lock acquired 🔄")

def outer():
    with rlock:
        print("Outer lock acquired 🔄")
        inner()  # Would deadlock with standard Lock!

outer()

# 53. Reentrant Locks: threading.RLock A standard `Lock` freezes if the same thread attempts to acquire it twice. An `RLock` (Reentrant Lock) allows the owning thread to acquire it multiple times without self-deadlocking 🔄. ```python import threading rlock = threading.RLock() def inner(): with rlock: print("Inner lock acquired 🔄") def outer(): with rlock: print("Outer lock acquired 🔄") inner() # Would deadlock with standard Lock! outer() ``` `RLock` tracks recursion level and the owner thread ID. The lock only truly releases when the outermost `with` context exits and lock count hits zero! 🔄 --- ### Question What happens if a thread tries to acquire a standard non-reentrant `threading.Lock` that it already holds? 🧠 - [ ] a. It deadlocks and blocks itself indefinitely waiting for release 🛑 - [ ] b. It raises a KeyError immediately - [ ] c. It clones the lock into a temporary thread - [ ] d. It releases the lock and terminates the program --- ### Challenge Import `threading`. Create `rlock = threading.RLock()`. Acquire it twice with nested `with rlock:` blocks and print `'Nested Lock Success'`. 🎯 <details> <summary>Solution</summary> ```python import threading rlock = threading.RLock() with rlock: with rlock: print("Nested Lock Success") ``` </details>

Checkpoint

What happens if a thread tries to acquire a standard non-reentrant `threading.Lock` that it already holds? 🧠

Practice

Import `threading`. Create `rlock = threading.RLock()`. Acquire it twice with nested `with rlock:` blocks and print `'Nested Lock Success'`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks