iMom0
iMom0

Reputation: 12931

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()

Upvotes: 16

Views: 5949

Answers (2)

daparic
daparic

Reputation: 4474

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.

Upvotes: 17

Otto Allmendinger
Otto Allmendinger

Reputation: 28278

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.

Upvotes: 15

Related Questions