threading.Event Coordinates Worker Shutdown

Workers wait on one shared Event flag: wait(timeout) sleeps without busy looping, set() wakes every waiter at once, and join() confirms the shutdown.

PythonResilience

Code

pythonsnippet
26 lines
import threading

# Workers wait on a shared Event instead of guessing when to stop:
# one flag flips every waiter at once for a graceful shutdown.
stop = threading.Event()

def worker(name: str, results: list) -> None:
    ticks = 0
    while not stop.is_set():
        ticks += 1
        stop.wait(timeout=0.05)  # Sleeps here, wakes early when set.
    results.append((name, ticks))

results: list = []
threads = [threading.Thread(target=worker, args=(f"worker-{i}", results)) for i in range(2)]
for thread in threads:
    thread.start()

stop.wait(timeout=0.2)  # Let both workers tick for a while.
stop.set()              # Every waiter wakes immediately.
for thread in threads:
    thread.join(timeout=1)

print("all workers stopped:", len(results) == len(threads))
for name, _ in sorted(results):
    print(name, "acknowledged the shutdown")

Output

Captured from a sandboxed run of this snippet in the build pipeline.

all workers stopped: True
worker-0 acknowledged the shutdown
worker-1 acknowledged the shutdown

What the code does

threading.Event Coordinates Worker Shutdown reduces to the function worker.

The cycling part of this snippet is while not stop.is_set().

The input results is mutated in place — callers that need the original must pass a copy.

Watch out for

  • Nothing third-party is pulled in; the snippet is dependency-free.
  • results is mutated in place — the value you pass will not be the same afterward.

Applying it

Entry signature: def worker(name: str, results: list) -> None

Expect labeled output — all workers stopped: — when the file runs.

Treat worker as the API: import it, and ignore the supporting code.

Statements that matter

def worker(name: str, results: list) -> None:
    ticks = 0
    while not stop.is_set():
        ticks += 1
        stop.wait(timeout=0.05)  # Sleeps here, wakes early when set.
    results.append((name, ticks))

Interactive Tools for This Topic

FAQ

Does `worker` modify its input?
Yes — `results` is mutated in place. Pass a copy if the caller needs the original preserved.
Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `threading`. The file defines `worker` at load time.