3

我尝试使用多处理来创建非阻塞 GUI。Multiprocessing.Pool.appy_async() 函数允许添加回调函数,从而在完成耗时的操作后轻松更新主 GUI。但是,单击 button1 时,以下代码仍会阻塞。如何修改它,以便在执行 button1 回调时, button2 仍然响应。我正在运行 python 2.7 和多处理 0.70a1。

from PySide.QtCore import *
from PySide.QtGui import *
import multiprocessing
import time
import sys


def f(x):
    '''This is a time-intensive function
    '''
    y = x*x
    time.sleep(2)
    return y


class MainWindow(QMainWindow): #You can only add menus to QMainWindows

    def __init__(self):
        super(MainWindow, self).__init__()
        self.pool = multiprocessing.Pool(processes=4)

        button1 = QPushButton('Connect', self)
        button1.clicked.connect(self.apply_connection)
        button2 = QPushButton('Test', self)
        button2.clicked.connect(self.apply_test)
        self.text = QTextEdit()

        vbox1 = QVBoxLayout()
        vbox1.addWidget(button1)
        vbox1.addWidget(button2)
        vbox1.addWidget(self.text)
        myframe = QFrame()
        myframe.setLayout(vbox1)

        self.setCentralWidget(myframe)
        self.show() #display and activate focus
        self.raise_()


    def apply_connection(self):
        result = self.pool.apply_async(f, [10], callback=self.update_gui)
        result.get(3)


    def update_gui(self, result):
        self.text.append('Applied connection. Result = %d\n' % result)


    def apply_test(self):
        self.text.append('Testing\n')


if __name__ == '__main__':
    app = QApplication(sys.argv)
    gui = MainWindow()
    app.exec_()
4

1 回答 1

3

result.get(3)阻塞 3 秒等待结果。不要调用get,回调将处理结果。

于 2013-06-24T10:54:19.590 回答