How to use multiprocessing.Pool correctly with PySide to create a non-blocking GUI

戏子无情 提交于 2020-01-02 07:13:45

问题


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_()

回答1:


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



来源:https://stackoverflow.com/questions/17272888/how-to-use-multiprocessing-pool-correctly-with-pyside-to-create-a-non-blocking-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!