Events (signal between threads)
What is an Event?
An EventEvent is a simple flag:
- one thread sets it
- other threads wait until itβs set
Example
event_example.py
import threading
import time
ready = threading.Event()
def waiter():
print("Waiting...")
ready.wait() # blocks
print("Go!")
def setter():
time.sleep(1)
ready.set()
t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=setter)
t1.start(); t2.start()
t1.join(); t2.join()event_example.py
import threading
import time
ready = threading.Event()
def waiter():
print("Waiting...")
ready.wait() # blocks
print("Go!")
def setter():
time.sleep(1)
ready.set()
t1 = threading.Thread(target=waiter)
t2 = threading.Thread(target=setter)
t1.start(); t2.start()
t1.join(); t2.join()Resetting an event
event.clear()event.clear()resets it to false.- Useful for repeated cycles.
π§ͺ Try It Yourself
Exercise 1 β threading.Event Set and Wait
Exercise 2 β Clear an Event
Exercise 3 β Event with Timeout
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
