実験と学習だけで、複数のプロセスでアクセスできる共有辞書を作成する方法は知っていますが、辞書を同期させる方法はわかりません。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)
これを機能させる方法に関するヘルプや提案は素晴らしいでしょう!