Interview Prep/Python for DevOps/Concurrency: threads, processes & asyncio

How do you stop a pool of workers cleanly on Ctrl-C or SIGTERM?

AdvancedConceptConcurrency: threads, processes & asyncio
Answer

Use a shared threading.Event that workers check between units of work, and on interrupt set it and cancel pending futures:

stop = threading.Event()
with ThreadPoolExecutor(max_workers=8) as pool:
    futures = [pool.submit(worker, item, stop) for item in items]
    try:
        for f in as_completed(futures):
            f.result()
    except KeyboardInterrupt:
        stop.set()
        pool.shutdown(wait=True, cancel_futures=True)   # 3.9+
        raise

Threads cannot be killed from outside, so long-running workers must cooperate by checking the event. Daemon threads die abruptly at exit, skipping cleanup.

All Python for DevOps questions Roadmap: Python for automation

More on Concurrency: threads, processes & asyncio