Code Explanation:
1️⃣ Importing Threading Module
import threading
Explanation
Imports Python’s threading module.
Used for creating threads and locks.
2️⃣ Creating an RLock
lock = threading.RLock()
Explanation
Creates a Reentrant Lock (RLock).
Special lock that allows same thread to acquire it multiple times.
๐ Unlike normal Lock, this avoids deadlock when re-acquired.
3️⃣ Defining Task Function
def task():
Explanation
Function that will run inside the thread.
4️⃣ First Lock Acquisition
with lock:
Explanation
Thread acquires the lock.
Ensures only one thread enters this block at a time.
5️⃣ Printing First Value
print("A")
Explanation
Prints:
A
6️⃣ Nested Lock Acquisition
with lock:
Explanation ⚠️ IMPORTANT
Same thread tries to acquire the lock again.
Since it's an RLock, this is allowed.
๐ With normal Lock, this would cause deadlock ❌
7️⃣ Printing Second Value
print("B")
Explanation
Prints:
B
8️⃣ Creating Thread
t = threading.Thread(target=task)
Explanation
Creates a thread that will execute task().
9️⃣ Starting Thread
t.start()
Explanation
Thread starts execution.
Runs task().
๐ Waiting for Completion
t.join()
Explanation
Main thread waits until task() finishes.
๐ค Final Output
A
B

0 Comments:
Post a Comment