Sunday, 20 December 2015

Python: Threads : RLock objects

A reentrant lock is just like a lock, main difference is that reentrant lock can be acquired multiple times by the same thread. It is not the case with threading.Lock, thread can acquire the lock only once.


MyThread.py
import threading

def fun1():
 global lock
 lock.acquire()
 print("I am in function 1")
 fun2()
 lock.release()

def fun2():
 global lock
 lock.acquire()
 print("I am in function 2")
 lock.release()
 
class MyThread(threading.Thread):
 def run(self):
  fun1()
  
global lock
lock = threading.Lock()
 
thread1 = MyThread(name="thread-1")

thread1.start()

$ python3 MyThread.py 
I am in function 1
^Z
[2]+  Stopped                 python3 MyThread.py

Observe the code, fun2 is called from fun1. Thread is already acquires the lock in fun1, so it is blocked in fun2. Now update the program by using threading.RLock object and re run.


MyThread.py
import threading

def fun1():
 global lock
 lock.acquire()
 print("I am in function 1")
 fun2()
 lock.release()

def fun2():
 global lock
 lock.acquire()
 print("I am in function 2")
 lock.release()
 
class MyThread(threading.Thread):
 def run(self):
  fun1()
  
global lock
lock = threading.RLock()
 
thread1 = MyThread(name="thread-1")

thread1.start()

$ python3 MyThread.py 
I am in function 1
I am in function 2

Difference between Lock and RLock
a.   Lock is acquired once, where as RLock can be acquired multiple times by the same thread.
b.   A reentrant lock must be released by the thread that acquired it. A Lock can be released by any thread.





Previous                                                 Next                                                 Home

No comments:

Post a Comment