6
我認爲我正確地遵循了python文檔,但我無法獲得我期待的結果。我基本上有一個數字列表,這些數字被傳遞給嵌套for循環的函數,輸出保存在字典中。如何訪問多處理共享字典?
下面的代碼:
from multiprocessing import Pool, Manager
list = [1,2,3,10]
dictionary = {}
def test(x, dictionary):
for xx in range(100):
for xxx in range(100):
dictionary[x]=xx*xxx
if __name__ == '__main__':
pool = Pool(processes=4)
mgr = Manager()
d = mgr.dict()
for N in list:
pool.apply_async(test, (N, d))
# Mark pool as closed -- no more tasks can be added.
pool.close()
# Wait for tasks to exit
pool.join()
# Output results
print d
這裏是預期的結果:
{1: 9801, 2: 9801, 3: 9801, 10: 9801}
的是什麼,我做錯了什麼建議?另外,我還沒有相信自己共享資源是最好的方法(考慮使用數據庫來維護狀態),所以如果我的方法完全有缺陷,或者有更好的方法在Python中執行此操作,請讓我知道。
謝謝,我不敢相信我犯了這麼簡單的錯誤。謝謝。至於一般的方法。我真正的代碼基本上需要引用現有的dict項目,如果它不存在以創建它(並且它確實存在以在新循環內處理它)。具體來說,它不適合我,但它很好地瞭解這種方法。我正在考慮一個數據庫(或將結果存儲在一個文件中),但並不確定。 – Lostsoul 2012-02-13 06:21:45