1 回答
TA贡献1797条经验 获得超6个赞
随着你每次都开始一个新的经理流程,所以你真的在嵌套经理(就像标题所说的那样),这不是它应该的方式Manager()。Manager().dict()相反,您需要做的是实例化一个Manager,然后在该 manager 实例上创建字典:
from multiprocessing import Process, Manager
from multiprocessing.managers import DictProxy
def task(test): # use parameter `test`, else you rely on forking
test['z'] += 1
test['y']['Y0'] += 5
if __name__ == '__main__':
with Manager() as m:
test = m.dict({'x': m.dict({'X0': 10, 'X1': 20}),
'y': m.dict({'Y0': 0, 'Y1': 0}),
'z': 0})
p = Process(target=task, args=(test,))
p.start()
p.join()
print(test)
print(test['y'])
# convert to normal dict before closing manager for persistence
# in parent or for printing dict behind proxies
d = {k: dict(v) if isinstance(v, DictProxy) else v
for k, v in test.items()}
print(d) # Manager already closed here
示例输出:
{'x': <DictProxy object, typeid 'dict' at 0x7f98cdaaa588>, 'y': <DictProxy object, typeid 'dict' at 0x7f98cda99c50>, 'z': 1}
{'Y0': 5, 'Y1': 0}
{'x': {'X0': 10, 'X1': 20}, 'y': {'Y0': 5, 'Y1': 0}, 'z': 1}
Process finished with exit code 0
Manager.Lock如果您计划从多个进程修改管理器对象,您还需要使用它。
添加回答
举报