Skip to content

Events (signal between threads)

diagram an Event is a latch, not a queue mermaid
It has one bit of state. Setting it releases every thread waiting at that moment and every thread that arrives afterwards, until somebody clears it. That makes it right for 'the configuration is loaded' or 'time to shut down', and wrong for handing over items, because there is nothing to hand over and no count.

An Event is a simple flag:

  • one thread sets it
  • other threads wait until it’s set
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.clear() resets it to false.
  • Useful for repeated cycles.
sketch An Event releases everyone, and stays open p5.js
Three threads park on wait(). One set() releases all of them at once -- not one, and not in turn. And because the flag stays set, a fourth thread arriving afterwards does not block at all. That last property is what distinguishes an Event from a notify, which a late arrival simply misses.
pch.quizTag pch.quizDefaultTitle
  1. Three threads are blocked in `ev.wait()`. One thread calls `ev.set()`. How many are released?

    pch.quizShowAnswer

    B — All three — Verified — all three logged 'released'. An Event is a latch on a shared flag, not a queue of permits.

  2. A thread calls `wait()` on an Event that is ALREADY set. What happens?

    pch.quizShowAnswer

    B — It returns immediately — Measured at 0.0000 s. An Event is level-triggered: it stays set, so late arrivals are not missed. `Condition.notify()` is edge-triggered and a late thread misses it entirely.

  3. When should you use a `Queue` instead of an `Event`?

    pch.quizShowAnswer

    B — When there is data to hand over — An Event carries one bit and no payload. A Queue transfers items, blocks the consumer when empty, and applies back-pressure to the producer when full.

  4. What does `ev.clear()` do to threads currently blocked in `wait()`?

    pch.quizShowAnswer

    B — Nothing — they were already released when it was set — `clear()` only affects who blocks from then on. Threads released by an earlier `set()` have already moved on.

Exercise 1 – threading.Event Set and Wait

Section titled “Exercise 1 – threading.Event Set and Wait”

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading