如何正确地使用multiprocessing.Pool与PySide一起创建一个非阻塞的GUI [英] How to use multiprocessing.Pool correctly with PySide to create a non-blocking GUI

查看:90
本文介绍了如何正确地使用multiprocessing.Pool与PySide一起创建一个非阻塞的GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am try to use multiprocessing to create a non-blocking GUI. The function Multiprocessing.Pool.appy_async() allows a callback function to be added, making it easy to update the main GUI after a time-intensive operation has been completed. However, the following code still blocks when clicking on button1. How can I modify this so that while the button1 callback is executing, button2 still responds. I am running python 2.7 and multiprocessing 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_()

推荐答案

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

result.get(3) blocks for 3 seconds to wait for the result. Don't call get, the callback will handle the result.

这篇关于如何正确地使用multiprocessing.Pool与PySide一起创建一个非阻塞的GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆