只是实验和学习,我知道如何创建一个可以通过多个进程访问的共享字典,但我不确定如何保持字典同步。defaultdict
,我相信,说明了我遇到的问题。
from collections import defaultdict
from multiprocessing import Pool, Manager, Process
#test without multiprocessing
s = 'mississippi'
d = defaultdict(int)
for k in s:
d[k] += 1
print d.items() # Success! result: [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
print '*'*10, ' with multiprocessing ', '*'*10
def test(k, multi_dict):
multi_dict[k] += 1
if __name__ == '__main__':
pool = Pool(processes=4)
mgr = Manager()
multi_d = mgr.dict()
for k in s:
pool.apply_async(test, (k, multi_d))
# Mark pool as closed -- no more tasks can be added.
pool.close()
# Wait for tasks to exit
pool.join()
# Output results
print multi_d.items() #FAIL
print '*'*10, ' with multiprocessing and process module like on python site example', '*'*10
def test2(k, multi_dict2):
multi_dict2[k] += 1
if __name__ == '__main__':
manager = Manager()
multi_d2 = manager.dict()
for k in s:
p = Process(target=test2, args=(k, multi_d2))
p.start()
p.join()
print multi_d2 #FAIL
第一个结果有效(因为它不使用multiprocessing
),但我在让它与multiprocessing
. 我不知道如何解决它,但我认为可能是因为它没有同步(并在稍后加入结果),或者可能是因为multiprocessing
我无法弄清楚如何设置defaultdict(int)
字典。
任何有关如何使其工作的帮助或建议都会很棒!