当工作线程从主线程调用函数时,按顺序运行代码

时间:2017-03-31 12:31:37

标签: python multithreading pyqt pyside python-multithreading

我在python中的应用程序中有一个工作线程,可防止GUI被冻结,因为它需要在应用程序中进行连续处理。工作线程在主线程上调用“执行”功能,该主线程经常处理繁重。

问题是当发生繁重的处理时,线程不会等待执行“执行”功能的代码并再次执行该功能。

代码:

import time
import sys
from PySide import QtCore, QtGui

class ServerThread(QtCore.QThread):

    def __init__(self, parent=None):
        QtCore.QThread.__init__(self)
        self.x = 0
        self.sleep_time = 1        

    def start_server(self):
        while True :
            print "\nBegin Thread: "+str(self.x)
            self.emit(QtCore.SIGNAL("dosomething(int)"), self.x)
            time.sleep(self.sleep_time)
            print "End Thread: "+str(self.x)
            self.x += 1

    def run(self):
        self.start_server()


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.thread = ServerThread()
        self.thread.start()
        self.connect(self.thread, QtCore.SIGNAL("dosomething(int)"), self.doing)

    def doing(self, x):
        print "--Begin Process: " + str(x)
        #Does some heavy processing
        h = 0
        for i in range(30000000) : 
            h = x ** 2
        print "--End Process: " + str(x)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    frame = MainWindow()
    frame.show()
    app.exec_()

我需要“执行”功能才能在最后一个完全执行时执行。

图像1显示当前输出,图2显示预期输出。

当前输出:

enter image description here

预期产出:

enter image description here

0 个答案:

没有答案
相关问题