Recently, I’ve been working on a Python project which has a third party library that provided some thread callbacks for its services. However, this particular library didn’t offer many interface options other than
threading.Event and I needed to control some callbacks of this library. Turns out that although
threading.Event is quite simple, it enables you to signal certain events between threads. Let’s see an example of how you can wake up a worker thread
thread_one by setting an event on
Essentially, when the
threading.Event object is instantiated it starts as false, and as soon as you call
threading.Event.wait() the thread will wait for the event to become true, which can be set by calling
threading.Event.set(). Plus, you can also set a timeout if that’s appropriate for your use case.
For more information, checkout official Python
threading.Event docs 1.
So here’s the execution of the previous code snippet:
As you can see, both threads almost started at the same time.
thread_two (Thread-2) is processing something and after two seconds (
time.sleep(2)), it is supposed to wake up
thread_one. As soon as
thread_one will wake up immediately. You can notice by the timestamp of the code execution that in fact,
thread_two woke up practically immediately after the
threading.Event was set.
That’s it. Quite straightforward, but totally handy when that’s all you’ve got to work with. Plus, certainly, this solution is better than a busy-wait loop.