Python subclassing process with parameter

二次信任 提交于 2020-01-13 12:15:12

问题


I'm trying to create an object but as a new process. I'm following this guide and came up with this code.

import multiprocessing as mp 
import time

class My_class(mp.Process):
    def run(self):
        print self.name, "created"
        time.sleep(10)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class()
    p2=My_class()
    p1.start()
    p2.start()  
    print 'main exited'

But here I'm unable to pass arguments to the object. I searched but found none. It's not like a normal multiprocess where we'd be doing something like:

p1 = multiprocessing.Process(target=My_class, args=('p1',10,))

to pass the arguments to the new process. But the multiprocessing for a class instance is different. For now I'm passing it the hard way like below.

import multiprocessing as mp 
import time

class My_class(mp.Process):
    my_vars={'name':'', 'num':0}
    def run(self):
        self.name=My_class.my_vars['name']
        self.num=My_class.my_vars['num']
        print self.name, "created and waiting for", str(self.num), "seconds"
        time.sleep(self.num)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class()
    p2=My_class()
    My_class.my_vars['name']='p1'
    My_class.my_vars['num']=20
    p1.start()
    My_class.my_vars['name']='p2'
    My_class.my_vars['num']=10
    p2.start()  
    print 'main exited'

Which is working fine. But I guess it may fail for complex arguments like a large list or object or something like that.

Is there any other method to pass the arguments??


回答1:


You can just implement an __init__ method for My_class, which takes the two parameters you want to provide:

import multiprocessing as mp 
import time

class My_class(mp.Process):
    def __init__(self, name, num):
        super(My_class, self).__init__()
        self.name = name
        self.num = num

    def run(self):
        print self.name, "created and waiting for", str(self.num), "seconds"
        time.sleep(self.num)
        print self.name, "exiting"
        self.x()

    def x(self):
        print self.name, "X"

if __name__ == '__main__':
    print 'main started'
    p1=My_class('p1', 20)
    p2=My_class('p2', 10)
    p1.start()
    p2.start()  
    print 'main exited'

You just need to be sure to call super(My_class, self).__init__() in your __init__ method, so that your class is properly initialized as a Process subclass.



来源:https://stackoverflow.com/questions/28711140/python-subclassing-process-with-parameter

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