为什么我的dict不会更新?不是DictProxy的目的是处理这样的案件吗?
from multiprocessing import Pool, Manager
def func(logtree):
logtree['x'] = 'x'
def main():
manager = Manager()
logtrees = manager.dict()
logtrees['a'] = {}
logtrees['b'] = {}
logtrees['c'] = {}
pool = Pool(processes=2)
for key in logtrees.keys():
pool.apply_async(func, args=(logtrees[key],))
pool.close()
pool.join()
print(logtrees)
if __name__ == '__main__':
main()
实际输出:{'a': {}, 'b': {}, 'c': {}}
所需的输出:{'a': {'x': 'x'}, 'b': {'x': 'x'}, 'c': {'x': 'x'}}
答案 0 :(得分:1)
我认为答案不正确。您用普通词典覆盖了经理。
logtrees = {key: dict(logtrees[key]) for key in logtrees.keys()}
您可以通过添加以下几行来观察这一点
from multiprocessing import Pool, Manager
def func(logtree):
logtree['x'] = 'x'
def main():
manager = Manager()
logtrees = manager.dict()
logtrees['a'] = manager.dict()
logtrees['b'] = manager.dict()
logtrees['c'] = manager.dict()
pool = Pool(2)
for key in logtrees.keys():
pool.apply_async(func, args=(logtrees[key],))
pool.close()
pool.join()
print(logtrees.__class__) # <-------------------------------------- here
logtrees = {key: dict(logtrees[key]) for key in logtrees.keys()}
print(logtrees)
print(logtrees.__class__) # <-------------------------------------- here
if __name__ == '__main__':
main()
输出:
<class 'multiprocessing.managers.DictProxy'>
{'a': {'x': 'x'}, 'b': {'x': 'x'}, 'c': {'x': 'x'}}
<class 'dict'>
我希望知识有所帮助
答案 1 :(得分:0)
问题解决了!
from multiprocessing import Pool, Manager
def func(logtree):
logtree['x'] = 'x'
def main():
manager = Manager()
logtrees = manager.dict()
logtrees['a'] = manager.dict()
logtrees['b'] = manager.dict()
logtrees['c'] = manager.dict()
pool = Pool(2)
for key in logtrees.keys():
pool.apply_async(func, args=(logtrees[key],))
pool.close()
pool.join()
logtrees = {key: dict(logtrees[key]) for key in logtrees.keys()}
print(logtrees)
if __name__ == '__main__':
main()