我正在 Windows 上编写多线程 Python 应用。
我曾经使用 ctrl-c
终止应用程序,但是一旦我添加了 threading.Timer
实例 ctrl-c
停止工作(或有时需要很长时间)。
怎么会这样?
拥有 Timer 线程和 ctrl-c
有什么关系?
更新:
我在 Python 的 thread documentation 中找到了以下内容:
Threads interact strangely with interrupts: the KeyboardInterrupt exception will be received by an arbitrary thread. (When the signal module is available, interrupts always go to the main thread.)
最佳答案
threading.Thread
(以及 threading.Timer
)的工作方式是每个线程都将自己注册到 threading
模块,然后interpreter exit 解释器将等待所有已注册的线程退出,然后再终止解释器。这样做是为了让线程真正完成执行,而不是让解释器从它们下面被残酷地移除。所以当你点击 ^C 时,主线程接收到信号,决定终止并等待计时器完成。
您可以设置线程daemonic(使用setDaemon
方法)使线程模块不等待这些线程,但如果它们恰好在执行Python 代码时解释器退出时,您会在退出期间遇到令人困惑的错误。即使您取消了 threading.Timer
(并将其设置为守护进程),它仍然可以在解释器被销毁时唤醒——因为 threading.Timer
的 cancel
方法只是告诉 threading.Timer
在唤醒时不要执行任何操作,但它必须实际执行 Python 代码才能做出决定。
没有优雅的方式来终止线程(当前线程除外),也没有可靠的方式来中断被阻塞的线程。一种更易于管理的计时器方法通常是事件循环,就像 GUI 和其他事件驱动系统为您提供的那样。使用什么完全取决于还有什么您的程序将要做什么。
关于python - 使用 threading.Timer 时 Ctrl-C 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6594284/