0

I am trying to create new process to run separate tasks using multiprocessing. below is a simple demo:

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
from multiprocessing import Process as mProcess

class MyWindow(QMainWindow):
    def __init__(self):
        super(MyWindow,self).__init__()
        self.initUI()
        
        self.processes = []

    def initUI(self):
        self.setGeometry(200, 200, 300, 300)
        self.setWindowTitle("Tech With Tim")

        self.b1 = QtWidgets.QPushButton(self)
        self.b1.setText("click me!")
        self.b1.clicked.connect(self.button_clicked)

    def dummyFunction(self):
        def f(text):
            print(text)
        p = mProcess(target=f, args=(100,))
        self.processes.append(p) 
        p.start()

    def button_clicked(self):
        self.dummyFunction()

def window():
    app = QApplication(sys.argv)
    win = MyWindow()
    win.show()
    sys.exit(app.exec_())


if __name__ == "__main__":    
    window()

But I got this error:

Can't pickle local object 'MyWindow.dummyFunction.<locals>.f'
.
.
OSError: [WinError 6] The handle is invalid
zezo
  • 445
  • 4
  • 16
  • Multi processing is quite difficult to manage, especially for Qt (and even more if you want signals/slots). Are you *really* sure that threading is not enough? What are you trying to achieve? – musicamante Feb 27 '22 at 08:48
  • @musicamante The tasks I am running are independent of the GUI and are heavy computations (for mathematical optimization). Besides, I want to control each process with its `pid` to `start()`, `suspend()`, and `terminate()` the process, I am not sure, I can do this with `thread/Qthread`, since it doesn't have `pid`. Even without the `signal/slot`, and calling `self.dummyFunction()` in the constructor, I still have same problem – zezo Feb 27 '22 at 09:15
  • You can start and stop threads as well, as long as their computation allows it and they are well implemented. Besides, if working with threads can be difficult, using multiprocessing is even worse, as they don't share memory resources, intercommunication is difficult and requires the ability of *pickling* objects (including functions). I strongly suggest you some careful studying about both threading and multiprocessing, as they should not be approached without deeply understanding their underlying aspects (especially with the latter). In any case: https://stackoverflow.com/q/8804830 – musicamante Feb 27 '22 at 13:00
  • 1
    @zezo In general, you should always make sure the target function is defined in the module-global scope so that it can be safely re-imported by multiprocessing. – ekhumoro Feb 27 '22 at 15:07
  • @ekhumoro. Thanks, I have defined the function globally, and it works – zezo Feb 27 '22 at 21:41

0 Answers0