简体   繁体   中英

Start multiprocessing.Process of method in class, from __init__()

How can I start a multiprocessing.Process from within __init__() of a class, targeting another function in that class? The class itself shall not be a process. __init__() shall refer to a class variable assigned in the class, not inside any function.

Working code:

import multiprocessing as mp
class SomeClass:
    def __init__(self):
        p_process1 = mp.Process(target=self.process1)
        p_process1.start()

    def process1(self):
        while True:
            pass

The code I want:

import multiprocessing as mp
class SomeClass:
    def __init__(self):
        self.p_process1.start()

    def process1(self):
        while True:
            pass
    p_process1 = mp.Process(target=process1)

If I now try to run the code I want, I get an error message:

Process Process-1:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap
    self.run()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/multiprocessing/process.py", line 93, in run
    self._target(*self._args, **self._kwargs)
TypeError: process1() missing 1 required positional argument: 'self'

Well the problem clearly states it: the multiprocessing calls it without parameters, and you however expect one: self . In this case you can solve it like:

import multiprocessing as mp

class SomeClass:
    def __init__(self):
        self.p_process1.start()

    
    
        while True:
            pass
    p_process1 = mp.Process(target=process1)

If however you need a reference to self , there is no other option than to construct the method in a context where you have a reference to self . After all if you fetch self.process1 , you do not get a reference to SomeClass.process1 , you obtain a function that is equal to functools.partial(SomeClass.process1,self=self) , so you actually have a function where self is filled in implicitly.

process1 is a bound function, it needs class instance as self to be the first arg when be called.

If you just want that arch, @property can help.

import multiprocessing as mp
class SomeClass:
    def __init__(self):
        self.p_process1.start()

    def process1(self):
        while True:
            pass

    @property
    def p_process1(self):
        return mp.Process(target=self.process1)

SomeClass()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM