当 QThreadPool 不为空时退出? [英] Quit when QThreadPool not empty?
问题描述
我有很多长时间运行的任务在我的 Python 应用程序的后台运行.我把它们都放在全局 QThreadPool
中.当用户退出时,所有这些后台任务都需要停止.
I have a lot of long running tasks that run in the background of my Python app. I put them all in the global QThreadPool
. When the user quits, all of those background tasks need to stop.
现在,我有以下代码:
app.aboutToQuit.connect(killAllThreads)
def killAllThreads():
QtCore.QThreadPool.globalInstance().waitForDone()
我看到了一些建议,即添加一个全局变量来说明应用程序是否应该退出,并让线程自行终止,但这听起来像是一个非常混乱和不雅的解决方案.您真的建议在后台任务的每一行代码之前添加一个检查以确保应用程序不应该退出吗?这是我必须添加的数百张支票.
I've seen suggestions to add a global variable that says whether the application should be quitting, and to have threads terminate themselves, but this sounds like a terribly messy and inelegant solution. Would you really propose adding a check before every line of code in a background task to make sure that the application shouldn't be quitting yet? That's hundreds of checks that I would have to add.
该建议似乎假设我的任务很简单和/或涉及复杂的清理工作,但实际上,我刚好相反:任务涉及数百行代码,每行代码都可能需要几秒钟,但根本不需要清理.
The suggestion seems to make the assumption that my tasks are simple and/or have complex clean ups involved, but actually, I have just the opposite: the tasks involve hundreds of lines of code, each of which can take several seconds, but no clean up needs to be done at all.
我听说简单地杀死线程是一个坏主意,因为这样就不能保证它们能正确清理,但由于不需要清理,这正是我想要做的.此外,可能会出现竞争条件,但同样,任务需要立即停止,所以我真的不在乎它们是否最终处于无效状态.
I've heard simply killing the threads would be a bad idea, as then they wouldn't be guaranteed to clean up properly, but as no clean up is necessary, that's exactly what I want to do. Additionally, race conditions could occur, but again, the tasks need to stop right now, so I really don't care if they end up in an invalid state.
所以我需要知道以下几点:
So I need to know the following:
- 如何获取
QThreadPool
中所有正在运行的线程的列表? - 我如何让他们放弃正在做的事情?
- How do I get a list of all the running threads in a
QThreadPool
? - How do I have them abort what they're doing?
推荐答案
使用守护进程,当主线程结束时它们会自动终止
use daemons, they are automatically terminated when the main thread is ended
from threading import Thread
t = Thread(target=self.ReadThread)
t.setDaemon(True)
这篇关于当 QThreadPool 不为空时退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!