如何确保 QApplication 及其 QThreads 全部关闭

How to make sure the QApplication and its QThreads are all closed

下面的代码创建了一个 QDialog,它启动了一个 QThread,该 QThread 获得了一个计算时间很长的函数。 QDialog 的 closeEvent() 方法已修改为终止已启动的 thread

如何确保 thread 仅在完成其正在处理的任务时才终止?使用 quit() 方法和 terminate() 方法停止线程有什么区别? thread 是否应该总是在主应用程序 window 关闭之前终止?为什么在 Mac OS X 上 Python 进程仍然在 Activity 监视器中列出,即使在主对话框关闭和线程终止后也是如此?

import threading
import Queue as Queue
import datetime

global queue
queue = Queue.Queue()


class Thread(QThread):
    def __init__(self, queue, parent):
        QThread.__init__(self, parent)
        self.queue = queue

    def run(self):
        while True:
            task = queue.get()
            output = task()
            queue.task_done()


def longToCalculate():
    for i in range(30000000):
        i += i
        if not i % 100000:
            print '%s ...still calculating ' % datetime.datetime.now()
    print 'calculation completed'
    return i


class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

    def closeEvent(self, event):
        # self.thread.quit()
        self.thread.terminate()
        event.accept()


class Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.queue = Queue.Queue()
        self.thread = Thread(queue=self.queue, parent=self)
        self.thread.start()
        queue.put(longToCalculate)

if __name__ == '__main__':
    app = QApplication([])
    dialog = Dialog()
    dialog.show()
    qApp.exec_()

这是一个不包含队列的示例代码。

import os, sys
import datetime

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

class Thread( QThread ):
    def __init__( self, parent ):

        QThread.__init__( self, parent )

    def run( self ):
        self.longToCalculate()

    def longToCalculate( self ):
        for i in range( 30000000 ):
            i += i

            if ( i % 1000000 == 0 ):
                print( '%s ...still calculating' % QDateTime.currentDateTime().toString() )

        print( 'calculation completed' )
        return i

class Dialog(QDialog):
    def __init__( self, parent = None ):

        QDialog.__init__( self, parent )

        self.thread = Thread( parent = self )
        self.thread.start()

        self.thread.finished.connect( self.threadComplete )

    def threadComplete( self ) :
        QMessageBox.information( self, "Thread complete", "The thread has finished running. This program wil automatically close now." )
        self.close()

    def closeEvent( self, cEvent ) :

        if self.thread.isRunning() :
            QMessageBox.information( self, "Thread running", "The thread is running. You cannot close this program." )
            cEvent.ignore()

        else :
            cEvent.accept()

if __name__ == '__main__':

    app = QApplication( sys.argv )

    dialog = Dialog()
    dialog.show()

    qApp.exec_()