' QThread:在线程仍在运行时被销毁'退出

时间:2015-02-25 08:46:42

标签: python multithreading qt pyqt pyside

我正试图找到一种方法来正确退出我的应用程序。当我退出时,收到错误QThread: Destroyed while thread is still running。我有一个线程用于将输出提供给QTextBrowser。什么应该是正确的退出方式?这就是我所拥有的:

class LogReceiver(QtCore.QObject):
    mysignal = QtCore.Signal(str)

    def __init__(self, queue, *args, **kwargs):
        QtCore.QObject.__init__(self, *args, **kwargs)
        self.queue = queue

    def run(self):
        while True:
            text = self.queue.get()
            self.mysignal.emit(text)

if __name__ == '__main__':
    queue = Queue()
    thread = QtCore.QThread()
    my_receiver = MyReceiver(queue)

    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()

    my_receiver.mysignal.connect(window.append_text)
    my_receiver.moveToThread(thread)
    thread.started.connect(my_receiver.run)
    thread.start()

    sys.exit(app.exec_())

退出时thread会以某种方式终止吗?请注意self.queue.get()阻止并等待文本。

由于

2 个答案:

答案 0 :(得分:3)

你需要重新构造while循环,这样它就不会无条件地阻塞。

您可以使用简单的标志和超时来执行此操作:

    def run(self):
        self.active = True
        while self.active:
            try:
                text = self.queue.get(timeout=1.0)
                self.mysignal.emit(text)
            except Empty:
                continue

所以现在队列无限期地阻止,并且每秒检查一次标志以查看是否应该退出循环。

修改

以下是基于您的代码的工作示例:

import sys
from queue import Queue, Empty
from PySide import QtCore, QtGui

class LogReceiver(QtCore.QObject):
    mysignal = QtCore.Signal(str)

    def __init__(self, queue, *args, **kwargs):
        QtCore.QObject.__init__(self, *args, **kwargs)
        self.queue = queue

    def run(self):
        self.active = True
        while self.active:
            try:
                text = self.queue.get(timeout=1.0)
                self.mysignal.emit('text')
            except Empty:
                continue
        print('finished')

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.queue = Queue()
        self.thread = QtCore.QThread(self)
        self.receiver = LogReceiver(self.queue)
        self.receiver.moveToThread(self.thread)
        self.thread.started.connect(self.receiver.run)
        self.thread.start()

    def closeEvent(self, event):
        print('close')
        self.receiver.active = False
        self.thread.quit()
        self.thread.wait()

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()

    sys.exit(app.exec_())

答案 1 :(得分:2)

尝试:

# previous code here
thread.start()
app.exec_()

thread.terminate()
thread.wait()
sys.exit(0)

基本上当exec_()结束时(QApplication通过关闭窗口关闭),您强制thread终止并wait()清除它。如果您的主题有一个事件循环,则可以调用quit()而不是terminate()terminate()通常不是一个好主意,请参阅:here

更理想的方法是在run()方法中添加标记

while !flag:
    do stuff

并将main更改为:

app.exec_()
flag = True
thread.wait()
sys.exit(0)

flag是全局变量。 <{1}}方法完成时QThread终止。