我正在使用 QThread 做一些周期性的后台工作,源代码看起来像这样
class Worker(QObject):
""" Separate QObject that does the work with affinity of
'DoStuffOnceASecond'"""
def __init__(self):
super(QWorker, self).__init__()
def doWork(self):
#... do work, post signal to consumer
class DoStuffOnceASecond(QThread):
def __init__(self):
super(DoStuffOnceASecond, self).__init__()
def run(self):
""" Setup "pullFiles" to be called once a second"""
self.timer= QTimer()
self.worker = Worker()
self.timer.setSingleShot(False)
self.timer.timeout.connect(self.worker.doWork)
self.timer.start(1000)
self.exec_()
我正在寻找终止此类线程的最佳方法。一种选择是将信号从主线程发布到该线程,从而在该线程中创建一个插槽。由于这些插槽作为事件循环的一部分执行,因此它们会被安全地拾取。但那样我就会 self 终止......我不确定这是否会很好地工作。
或者我想知道,既然线程应该意识到它正在运行一个事件循环,那么在这个线程上调用 exit()
是否安全? documentation 似乎表明这是可以的:
After calling this function, the thread leaves the event loop and returns from the call to QEventLoop::exec(). The QEventLoop::exec() function returns returnCode.
我认为“离开事件循环”意味着它将允许当前事件完成处理。还是 QThread 会立即终止?
这里的代码是 python(pyside 1.10,python 2.7),但这可以很容易地应用于任何使用 QThread 的 QT 代码。
最佳答案
如果您不介意返回码为 0,则无需声明任何额外的插槽。那么您可以使用 already defined quit()
插槽,它只是在您的线程上调用 exit(0)
。关于你害怕“ self 终止”——你不是在终止线程,只是退出它的事件循环。您可以随时通过再次调用 exec() 来启动它。你仍然对你的线程很好,所以一切都应该“工作得很好”。 QThread::terminate 可以立即终止但这意味着当上述方法失败时,作为最后的绝望手段杀死线程。
关于python - 当 QThread 有事件队列时,用 exit() 终止线程是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11959401/