Skip to content

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 coffee

Was this page helpful?

Let us know how we did