在 Python 线程中处理信号
我有一个用 Python 编写的线程应用程序,每当通过 Ctrl+C 或有时使用 Kill 接收到中断时,应用程序就会挂起。堆栈跟踪是从一个线程显示的,但应用程序仍保留在前台,我通常必须使用 Ctrl+Z 将其置于后台,然后试图杀死它。
在线程应用程序内部处理信号和键盘中断的正确方法是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果在启动每个线程之前设置newthread.daemon = True,则当主线程退出时,线程将自动被终止。这并不完全是您要问的,但从您所描述的情况来看,这听起来可能值得了解。
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.我解决这个问题的方法是制作一个可以保存线程列表的模块。该模块还有一个方法可以杀死该列表中的每个线程。我注册了此方法,以便在收到
SIGINT
信号时调用。最后,我为 Thread 创建了一个包装类,它将自动将创建的实例添加到线程列表中。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 forThread
that would automatically add the created instance to the list of threads.CPython 线程:中断 涵盖了 Python 线程中信号发生的情况,以及针对您的问题的各种解决方案。这是一本很好的读物。
CPython Threading: Interrupting covers what happens to signals in Python threads, and various solutions to your problem. It is a good read.
使用 signal 模块 并在此处继续阅读 Python 中的信号处理程序和日志记录了解可能存在的陷阱。
为了捕获用户的 Ctrl+C 操作,您必须配置 SIGINT 的 >signal 处理程序。
在信号处理程序中通知(消息队列或 RLock 同步属性访问)您的线程要关闭,或者您打算做什么。
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 forSIGINT
.Within the signal handler notify (message queues or RLock synchronized attribute access) your threads to shutdown, or what ever you intent to do.