Does Event
and Lock
do the same thing in these scenes?
class MyThread1(threading.Thread):
def __init__(event):
self.event = event
def run(self):
self.event.wait()
# do something
self.event.clear()
another:
class MyThread2(threading.Thread):
def __init__(lock):
self.lock = lock
def run(self):
self.lock.acquire()
# do something
self.lock.release()
A Lock object can not be acquired again by any thread unless it is released by the thread which is accessing the shared resource. An RLock object can be acquired numerous times by any thread. A Lock object can be released by any thread. An RLock object can only be released by the thread which acquired it.
A primitive lock is a synchronization primitive that is not owned by a particular thread when locked. In Python, it is currently the lowest level synchronization primitive available, implemented directly by the _thread extension module. A primitive lock is in one of two states, “locked” or “unlocked”.
Yes, it is. It's a synchronization primitive for this purpose exactly.
The wait() method is known as a method of the event class in the Python threading module to release the execution of an event when its internal flag is set to false, which will cause the current block or event to be released until the internal flag is set to true.
If you wait on an event, the execution stalls until an event.set()
happens
event.wait() # waits for event.set()
Acquiring a lock only stalls if the lock is already acquired
lock.acquire() # first time: returns true
lock.acquire() # second time: stalls until lock.release()
Both classes have different use cases. This article will help you understand the differences.
Practically speaking, I found the difference between Event versus Lock in python to be:
There could still be more differences, but the above is the most obvious to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With