Handling Signals in Python Threads

2019-03-20 04:58发布

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?

4条回答
太酷不给撩
2楼-- · 2019-03-20 05:25

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楼-- · 2019-03-20 05:29

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

查看更多
姐就是有狂的资本
4楼-- · 2019-03-20 05:40

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.

查看更多
倾城 Initia
5楼-- · 2019-03-20 05:40

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.

查看更多
登录 后发表回答