Multithreading 如何在使用moveToThread时正确退出PyQt5中的QThread

Multithreading 如何在使用moveToThread时正确退出PyQt5中的QThread,multithreading,python-3.x,pyqt,pyqt5,qthread,Multithreading,Python 3.x,Pyqt,Pyqt5,Qthread,我正在尝试在线程完成处理后退出该线程。我正在使用moveToThread。我试图通过在插槽中调用self.thread.quit()从主线程退出工作线程。这是行不通的 我发现了几个使用moveToThread启动线程的示例,比如下面这个。但我找不到退出的方法 from PyQt5.QtCore import QObject, QThread from PyQt5.QtCore import pyqtSlot, pyqtSignal from PyQt5.QtWidgets import QMai

我正在尝试在线程完成处理后退出该线程。我正在使用moveToThread。我试图通过在插槽中调用self.thread.quit()从主线程退出工作线程。这是行不通的

我发现了几个使用moveToThread启动线程的示例,比如下面这个。但我找不到退出的方法

from PyQt5.QtCore import QObject, QThread
from PyQt5.QtCore import pyqtSlot, pyqtSignal
from PyQt5.QtWidgets import QMainWindow

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        print("Base init")
        self.start_thread()

    @pyqtSlot(int)
    def onFinished(self, i):
        print("Base caught finished, {}".format(i))
        self.thread.quit()
        print('Tried to quit thread, is the thread still running?')
        print(self.thread.isRunning())

    def start_thread(self):
        self.thread = QThread()
        self.w = Worker()
        self.w.finished1[int].connect(self.onFinished)
        self.w.moveToThread(self.thread)
        self.thread.started.connect(self.w.work)
        self.thread.start()

class Worker(QObject):
    finished1 = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        print("Worker init")

    def work(self):
        print("Worker work")
        self.finished1.emit(42)


if __name__ == "__main__":
    import sys
    from PyQt5.QtWidgets import QApplication

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

sys.exit(app.exec_())
这是我所有打印功能的输出(当然没有颜色):


尝试多次运行脚本。调用self.thread.isRunning()的结果是否总是相同的?在检查线程是否仍在运行之前,请尝试添加对time.sleep(1)的调用。注意到有什么不同吗


请记住,您正在从程序的主线程调用另一个线程,根据定义,这是异步的。在执行下一条指令之前,您的程序不会等待确认
self.thread.quit()
已完成。

谢谢!你是对的。这根线终于断了。print(self.thread.isRunning())在添加时间后显示False。sleep(1)
Base init
Worker init
Worker work
Base caught finished, 42
Tried to quit thread, is the thread still running?
True