Pool within a Class in Python

后端 未结 3 613
清酒与你
清酒与你 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: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()
    
    

提交回复
热议问题