Thread synchronization with RLock
If we want only the thread that acquires a lock to release it, we must use a RLock()
object. Similar to the Lock()
object, the RLock()
object has two methods: acquire()
and release()
. RLock()
is useful when you want to have a thread-safe access from outside the class and use the same methods from inside the class.
How to do it…
In the sample code, we introduced the Box
class, which has the methods add()
and remove()
, respectively, that provide us access to the execute()
method so that we can perform the action of adding or deleting an item, respectively. Access to the execute()
method is regulated by RLock()
:
import threading import time class Box(object): lock = threading.RLock() def __init__(self): self.total_items = 0 def execute(self,n): Box.lock.acquire() self.total_items += n Box.lock.release() def add(self): Box.lock.acquire() self.execute(1) Box.lock.release() def remove(self...