Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference of Event and Lock in python threading module?

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()
like image 497
iMom0 Avatar asked Jul 12 '12 06:07

iMom0


People also ask

What does lock do in threading Python?

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.

What is lock Python?

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”.

Is threading event thread safe?

Yes, it is. It's a synchronization primitive for this purpose exactly.

What does event Wait do in Python?

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.


2 Answers

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.

like image 62
Otto Allmendinger Avatar answered Oct 12 '22 12:10

Otto Allmendinger


Practically speaking, I found the difference between Event versus Lock in python to be:

  • An event can have many waiters and when the event is set or fired, ALL these waiters will wake up.
  • A lock can have many waiters and when the lock is released, only one waiter will wake up and as a result will acquire the lock.

There could still be more differences, but the above is the most obvious to me.

like image 33
eigenfield Avatar answered Oct 12 '22 13:10

eigenfield