简体   繁体   中英

Handling Signals in Python Threads

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?

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.

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM