我正在尝试使用 Manager() 在进程之间共享字典并尝试了以下代码:
from multiprocessing import Manager, Pool
def f(d):
d['x'] += 2
if __name__ == '__main__':
manager = Manager()
d = manager.dict()
d['x'] = 2
p= Pool(4)
for _ in range(2000):
p.map_async(f, (d,)) #apply_async, map
p.close()
p.join()
print (d) # expects this result --> {'x': 4002}
使用 map_async 和 apply_async,打印的结果总是不同的(例如 {'x': 3838}, {'x': 3770})。但是,使用 map 会给出预期的结果。另外,我尝试使用 Process 而不是 Pool,结果也不同。
有什么见解吗?非阻塞部分和竞态条件不是由经理处理的吗?