When running background threads, the common way to stop threads on SIGINT appears to be to either mark them as daemon threads, and just exit the main program, or to set a flag:
import signal
import sys
from threading import Event, Thread
kill_threads = Event()
# Define signal handler
def signal_handler(*args, **kwargs):
kill_threads.set()
sys.exit(0)
# Register the signal handler callback function
signal.signal(signal.SIGINT, signal_handler)
def my_thread():
while not kill_threads.is_set():
# Do stuff
Thread(target=my_thread).start()
This works fine, as long as the operation you're doing in your thread is non-blocking. That's not always an option. If you're dealing with an external library that you didn't write, and don't control the source code of, having that library run in a non-blocking way isn't always possible.
If your thread can't check a flag to know when to exit because it's running a blocking function, what's the best way to interrupt it?