Why Python signal handlers are always executed in the main Python thread of the main interpreter?
Sarthak Shah
Senior Software Engineer @ LibelluleMonde | Passionate about Embedded, IoT & Edge Computing | Machine Learning | Python Django, Computer Vision, AWS | Ex L&T, Xylem Inc.
Even if the signal was received in another thread, Python signal handlers are always executed in the main Python thread of the main interpreter.
This means that signals can’t be used as a means of inter-thread communication. You can use the synchronization primitives from the?threading?module instead.
Besides, only the main thread of the main interpreter is allowed to set a new signal handler.
When you install a signal handler in python, the runtime installs a C signal handler stub that just sets a flag. The interpreter checks the flag between bytecode instructions and then invokes the python signal handler.
That means that signals handlers can only run between bytecode operations. If the main python thread is executing C code, it won't be able to handle signals until the current operation completes. There is some provision for SIGINT (i.e., control-C) to abort blocked IO, but only in the main thread.
Example of signal.signal() usage:
import signal
def my_handler(signum, frame):
print("It took too long")
raise TimeoutError("took too long")
signal.signal(signal.SIGINT, my_handler)
signal.alarm(5)
def get_data():
import time
time.sleep(20)
get_data()