multiprocessing.Pool,不会永久影响类变量

时间:2015-09-09 13:08:17

标签: python python-multiprocessing

我正在使用multiprocessing.Pool在多个处理器上分配方法的工作。当我向字典添加内容时,它会在执行该方法后丢失。这是为什么?以及如何规避它?

from multiprocessing import Pool


class Agent:
    def __init__(self):
        self.test_dict = {}

    def apply(self, num):
        # something very processor intensive here
        self.test_dict[num] = num
        print 'inside ', self.test_dict

def F(x):
    agent, i = x
    return agent.apply(i)

class SeriesInstance(object):
    def __init__(self):
        self.agent = Agent()
        self.F = F

    def run(self):
        p = Pool()

        for i in range(5):
            out = p.map(F, [(self.agent, i),])

            print 'outside', self.agent.test_dict


        p.close()
        p.join()

        return out

if __name__ == '__main__':
    SeriesInstance().run()

输出是这个,但外面应该等于内部

inside  {0: 0}
outside {}
inside  {1: 1}
outside {}
inside  {2: 2}
outside {}
inside  {3: 3}
outside {}
inside  {4: 4}
outside {}

1 个答案:

答案 0 :(得分:1)

请检查Sharing state between processes并阅读服务器进程部分。您似乎必须创建一个管理器并使用该管理器来创建dict类中使用的Agent个实例。

from multiprocessing import Process, Manager

def f(d, l):
    d[1] = '1'
    d['2'] = 2
    d[0.25] = None
    l.reverse()

if __name__ == '__main__':
    with Manager() as manager:
        d = manager.dict()
        l = manager.list(range(10))

        p = Process(target=f, args=(d, l))
        p.start()
        p.join()

        print(d)
        print(l)