Python how to do multiprocessing inside of a class?

后端 未结 3 689
余生分开走
余生分开走 2021-02-01 03:43

I have a code structure that looks like this:

Class A:
  def __init__(self):
    processes = []
    for i in range(1000):
      p = Process(target=self.RunProces         


        
3条回答
  •  旧巷少年郎
    2021-02-01 04:21

    There are a couple of syntax issues that I can see in your code:

    • args in Process expects a tuple, you pass an integer, please change line 5 to:

      p = Process(target=self.RunProcess, args=(i,))

    • list.append is a method and arguments passed to it should be enclosed in (), not [], please change line 6 to:

      processes.append(p)

    As @qarma points out, its not good practice to start the processes in the class constructor. I would structure the code as follows (adapting your example):

    import multiprocessing as mp
    from time import sleep
    
    class A(object):
        def __init__(self, *args, **kwargs):
            # do other stuff
            pass
    
        def do_something(self, i):
            sleep(0.2)
            print('%s * %s = %s' % (i, i, i*i))
    
        def run(self):
            processes = []
    
            for i in range(1000):
                p = mp.Process(target=self.do_something, args=(i,))
                processes.append(p)
    
            [x.start() for x in processes]
    
    
    if __name__ == '__main__':
        a = A()
        a.run()
    

提交回复
热议问题