Handling Signals in Python Threads

2019-03-20 05:02发布

问题:

I have a threaded application written in Python, and whenever an interrupt is received via Ctrl+C or sometimes with kill, the application will hang. A stack trace is presented from one thread, but the application remains in the foreground, and I usually have to background it with Ctrl+Z then attempt to kill it.

What is the proper way of handling signals and keyboard interrupts inside of a threaded application?

回答1:

If you set newthread.daemon = True before starting each thread, the threads will automatically be killed when the main thread exits. That's not precisely what you were asking, but from what you've described, it sounds like it could be worth knowing.



回答2:

The way I worked around this issue was to make a module that could kept a list of threads. The module also had a method that killed every thread in that list. I registered this method to be called when the SIGINT signal was received. Lastly, I created a wrapper class for Thread that would automatically add the created instance to the list of threads.



回答3:

CPython Threading: Interrupting covers what happens to signals in Python threads, and various solutions to your problem. It is a good read.



回答4:

Use the signal module and continue reading here Signal handlers and logging in Python about possible pitfalls.

In order to catch Ctrl+C actions from the user you have to profice a signal handler for SIGINT.

Within the signal handler notify (message queues or RLock synchronized attribute access) your threads to shutdown, or what ever you intent to do.