Lesson 8 / 25

External Stops and Cancellation

Let users and systems cancel a running loop cleanly.

Check a flag between steps

Users press Cancel, servers shut down, and parent jobs time out. The loop should check a cancellation flag at a safe point between turns, not in the middle of writing a file. When set, it stops, saves its state and reports "cancelled" rather than failing mysteriously.

A cancellation event

threading.Event is a thread-safe flag. Another thread (a request handler, a signal handler) calls cancel.set().

import threading
cancel = threading.Event()

for step in range(max_steps):
    if cancel.is_set():
        save_state(messages)
        return {"status": "cancelled", "step": step}
    ...  # call, inspect, act, append

Quick check: Where is the safest place to check a cancel flag?

  • In the middle of a file write
  • Between turns, at a safe point
  • Never
  • Only after the process exits
Answer

Between turns, at a safe point — Checking between turns avoids leaving half-finished side effects.