Pool within a Class in Python

后端 未结 3 591
清酒与你
清酒与你 2021-01-02 04:50

I would like to use Pool within a class, but there seems to be a problem. My code is long, I created a small-demo variant to illustrated the problem. It would be great if yo

相关标签:
3条回答
  • 2021-01-02 05:12

    It looks like because of the way the function gets passed to the worker threads (pickling) you can't use instance methods unfortunately. My first thought was to use lambdas, but it turns out the built in pickler can't serialize those either. The solution, sadly, is just to use a function in the global namespace. You can still make it an instance attribute though, take a look:

    from multiprocessing import Pool
    
    def F(x):
        return x * x
    
    class SeriesInstance(object):
        def __init__(self):
            self.numbers = [1,2,3]
            self.F = F
    
        def run(self):
            p = Pool()
            out = p.map(self.F, self.numbers)
            p.close()
            p.join()
            return out
    
    if __name__ == '__main__':
        print SeriesInstance().run()
    
    0 讨论(0)
  • 2021-01-02 05:21

    You can also use multiprocessing with static functions in the class.

    0 讨论(0)
  • 2021-01-02 05:22

    You have an error, because pickle can't serialize instancemethod. So you should use this tiny workaround:

    from itertools import repeat
    from multiprocessing import Pool
    
    
    class SeriesInstance:
        def __init__(self):
            self.numbers = [1, 2, 3]
    
        def F(self, x):
            return x * x
    
        def run(self):
            p = Pool()
            print(list(p.starmap(SeriesInstance.F, zip(repeat(self), self.numbers))))
    
    
    if __name__ == '__main__':
        SeriesInstance().run()
    
    
    0 讨论(0)
提交回复
热议问题