1

我正在尝试学习如何在 python 程序中使用线程。我正在使用 PySide 和 QThreads,因为之后我将使用 PySide 实现 gui。

至少我认为,我已经理解了线程的主要概念。但我仍然对事件循环感到困惑。我认为这是我的应用程序的问题。

这是一个我无法正常工作的示例应用程序。在我的主类中,我有几个工作线程,我希望他们向主类报告他们的进度。但主程序不会实时打印进度消息。

我怎样才能让它工作?

from PySide import QtCore
import time, sys

class MyWorkerThread(QtCore.QThread):
    message = QtCore.Signal(str)

    def __init__(self, id, parent=None):
        super(MyWorkerThread, self).__init__(parent)
        self.id = id

    def run(self):
        for i in range(10):
            self.message.emit("%d: %d" % (self.id, i))
            time.sleep(0.2)

class MainProgram():
    def __init__(self, parent=None):
        self.threads = []

        self.addWorker(MyWorkerThread(1))
        self.addWorker(MyWorkerThread(2))

    def addWorker(self, worker):
        worker.message.connect(self.printMessage, QtCore.Qt.QueuedConnection)
        self.threads.append(worker)

    def startWorkers(self):
        for worker in self.threads:
            worker.start()
            worker.wait()
        self.workersFinished()

    def workersFinished(self):
        QtCore.QCoreApplication.instance().quit()

    @QtCore.Slot(str)
    def printMessage(self, text):
        sys.stdout.write(text+'\n')
        sys.stdout.flush()

if __name__ == '__main__':
    app = QtCore.QCoreApplication(sys.argv)
    m = MainProgram()
    m.startWorkers()
    sys.exit(app.exec_())
4

1 回答 1

5

worker.wait()是问题所在。这个调用会阻塞主线程(在这种情况下是一个正在运行的事件循环),直到 worker 完成它的工作。

这是一个稍有改动的版本(我已经评论了我的改动):

from PySide import QtCore
import time, sys

class MyWorkerThread(QtCore.QThread):
    message = QtCore.Signal(str)

    def __init__(self, id, parent=None):
        super(MyWorkerThread, self).__init__(parent)
        self.id = id

    def run(self):
        for i in range(10):
            self.message.emit("%d: %d" % (self.id, i))
            time.sleep(0.2)

class MainProgram():
    def __init__(self, parent=None):
        self.threads = []

        self.addWorker(MyWorkerThread(1))
        self.addWorker(MyWorkerThread(2))

    def addWorker(self, worker):
        worker.message.connect(self.printMessage, QtCore.Qt.QueuedConnection)
        # connect the finished signal to method so that we are notified
        worker.finished.connect(self.workersFinished)
        self.threads.append(worker)

    def startWorkers(self):
        for worker in self.threads:
            worker.start()
            # no wait, no finished. you start the threads and leave.

    def workersFinished(self):
        if all(worker.isFinished() for worker in self.threads):
            # wait until all the threads finished
            QtCore.QCoreApplication.instance().quit()

    @QtCore.Slot(str)
    def printMessage(self, text):
        sys.stdout.write(text+'\n')
        sys.stdout.flush()

if __name__ == '__main__':
    app = QtCore.QCoreApplication(sys.argv)
    m = MainProgram()
    m.startWorkers()
    sys.exit(app.exec_())
于 2012-04-06T13:51:28.997 回答