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.
More on Concurrency: threads, processes & asyncio
What is the GIL, and what does it mean for DevOps scripts?IntermediateHow do you use `ThreadPoolExecutor` for parallel API calls?BeginnerThreads vs processes vs asyncio: how do you choose?IntermediateWhat is a race condition, and how do you prevent one in threaded code?IntermediateHow does a producer/consumer pattern with `queue.Queue` work?AdvancedWhat are coroutines, `async def` and `await`?Intermediate