Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?

后端 未结 3 1160
[愿得一人]
[愿得一人] 2020-11-29 01:06

I am trying to write an application that applies a function concurrently with a multiprocessing.Pool. I would like this function to be an instance method (so I

3条回答
  •  遥遥无期
    2020-11-29 01:08

    Here is a easier way work in Python 2, just wrap the original instance method. Works well on macOS and Linux, not work on Windows, tested Python 2.7

    from multiprocessing import Pool
    
    class Person(object):
        def __init__(self):
            self.name = 'Weizhong Tu'
    
        def calc(self, x):
            print self.name
            return x ** 5
    
    
    def func(x, p=Person()):
        return p.calc(x)
    
    
    pool = Pool()
    print pool.map(func, range(10))
    

提交回复
热议问题