Search code examples
pythonblockingpython-multithreading

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

Solution

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