PYQt:多个线程按顺序运行

时间:2014-05-21 13:40:09

标签: python multithreading qt

我试图在我的pyqt应用程序中使用Qt线程,以避免UI运行缓慢或挂起进行长时间的过程,但是,经过大量的试验,我设法运行代码没有错误,但我仍然我没有看到任何变化,除了UI运行完全相同.... 我试图简化代码,下面的示例基本上是我想要做的,但是包含了更多的细节和GUI加载(只要我没有使用QtGui.QApplication.processEvents(),它现在就被冻结了)。我试图多次调用相同的方法,每次期望一个线程运行,因此不挂起UI。

import sys, traceback
import os
import subprocess
import time
import psutil
import signal
from PyQt4 import QtCore,QtGui

class ProcessController (QtCore.QObject):
        processCmdDone = QtCore.pyqtSignal()

        @QtCore.pyqtSlot()
        def execCmd(self, cmd):
                print "started execution of execCmd" + cmd
                for  i in range(10000000000):
                        #any command process
                        pass
                self.processCmdDone.emit()
                print "ended execution of cmd " + cmd

class Build (QtCore.QObject):
        def starting (self,cmd):
                process_inst = ProcessController()
                thread = QtCore.QThread(self)
                process_inst.moveToThread(thread)
                process_inst.processCmdDone.connect(thread.quit)
                thread.started.connect(self.printstarted)                      
                thread.started.connect(lambda: process_inst.execCmd(cmd))
                thread.finished.connect(self.printdone)
                thread.start()

        def printdone(self):
                print "thread done"

        def printstarted(self):
                print "thread started"

if __name__=="__main__":
        app = QtGui.QApplication(sys.argv)
        build_inst = Build()
        build_inst.starting("cmd1")
        build_inst.starting("cmd2")
        build_inst.starting("cmd3")
        app.exec_()

输出表明在上一个命令完成之前没有命令开始执行,空for循环用于在execCmd期间给出某种延迟:

thread started
started execution of execCmd cmd1
ended execution of cmd cmd1
thread started
thread started
started execution of execCmd cmd2
ended execution of cmd cmd2
started execution of execCmd cmd3
ended execution of cmd cmd3
thread done
thread done
thread done

我在某地读过python解释器可能不允许线程化,但我怎样才能确定是否是这种情况或我的编码问题?我非常感谢你的帮助。

0 个答案:

没有答案