Python 多处理,共享类实例不起作用

时间:2021-03-16 06:37:43

标签: python multiprocessing

我想根据某些条件将任务发送到共享类内部的POOL。但是我得到了一些意想不到的结果,如下所示。

• 为什么 len(self.map) 是 0,而不是 100。

• 我是否必须重构我的代码才能实现这个目标。

from multiprocessing import Pool
from multiprocessing.managers import BaseManager

pool = None

def doSomething(obj, *args):
    obj.doSomething(*args)

class SharedClass:
    def __init__(self):
        global pool
        self.map = set()
        pool = Pool(4)

    def someCondition(self):
        # the condition is rely on the instance, here is just an example
        return True

    def go(self, n):
        global pool
        for i in xrange(n):
            if self.someCondition():
                # pass the shared class to other process
                pool.apply_async(doSomething, (self, i))

        pool.close()
        pool.join()

        # got AssertionError here
        # why the len of self.map is 0
        assert len(self.map) == 100

    def doSomething(self, n):
        # this should change the same SharedClass instance?
        self.map.add(n)


class MyManager(BaseManager):
    pass

MyManager.register("SharedClass", SharedClass)

def main():
    manager = MyManager()
    manager.start()
    obj = manager.SharedClass()
    obj.go(100)

if __name__ == "__main__":
    main()

0 个答案:

没有答案
相关问题