无法更新多重处理的manager.dict()中的嵌套字典值 [英] Unable to update nested dictionary value in multiprocessing's manager.dict()
问题描述
我正在尝试更新多处理模块的manager.dict()的嵌套字典中的键,但无法这样做.它不会更新值,也不会引发任何错误.
I am trying to update a key in a nested dictionary of multiprocessing module's manager.dict() but not able to do so. It doesn't update the value and doesn't throw any error too.
代码:
import time
import random
from multiprocessing import Pool, Manager
def spammer_task(d, token, repeat):
success = 0
fail = 0
while success+fail<repeat:
time.sleep(random.random()*2.0)
if (random.random()*100)>98.0:
fail+=1
else:
success+=1
d[token] = {
'status': 'ongoing',
'fail': fail,
'success': success,
'repeat': repeat
}
print d[token]['status']
d[token]['status'] = 'complete'
return
p = Pool()
m = Manager()
d = m.dict()
p.apply_async(spammer_task (d, 'abc', 5))
print d
输出:
进行中
{'abc':{'状态':'进行中','失败':0,'重复':5,'成功':5}}
{'abc': {'status': 'ongoing', 'fail': 0, 'repeat': 5, 'success': 5}}
我的期望是,当while循环结束时,它应该使d ['abc'] ['status'] =完成.但是在最终打印中,它仅将状态打印为进行中".
My expectations are that as soon as while loop ends, it should make d['abc']['status'] = complete. But on final print it prints its status as 'ongoing' only.
推荐答案
不知道为什么,但是Manager DictProxy对象似乎无法处理嵌套部分的变异.该代码有效:
not sure why, but the Manager DictProxy object cant seems to handle mutating a nested part. this code works:
import time
import random
from multiprocessing import Pool, Manager
def spammer_task(d, token, repeat):
success = 0
fail = 0
while success+fail<repeat:
time.sleep(random.random()*2.0)
if (random.random()*100)>98.0:
fail+=1
else:
success+=1
d[token] = {
'status': 'ongoing',
'fail': fail,
'success': success,
'repeat': repeat,
}
print d[token]['status']
foo = d[token]
foo['status'] = 'complete'
d[token] = foo
return
p = Pool()
m = Manager()
d = m.dict()
p.apply_async(spammer_task(d, 'abc', 5))
print d
这篇关于无法更新多重处理的manager.dict()中的嵌套字典值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!