2012-02-13 41 views
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中執行此操作,請讓我知道。

回答

3

變化test的定義:

def test(x, d): 
    for xx in range(100): 
     for xxx in range(100): 
      d[x]=xx*xxx 

否則你只是增加一些全球dictionary(不同步),從​​不日後訪問。


至於一般的做法,我覺得這個特別在共享字典上有很多爭用。你是否真的必須儘快從每個進程更新它?在每個過程中累積批量的部分結果,並且稍後更新共享對象應該會更好。

+0

謝謝,我不敢相信我犯了這麼簡單的錯誤。謝謝。至於一般的方法。我真正的代碼基本上需要引用現有的dict項目,如果它不存在以創建它(並且它確實存在以在新循環內處理它)。具體來說,它不適合我,但它很好地瞭解這種方法。我正在考慮一個數據庫(或將結果存儲在一個文件中),但並不確定。 – Lostsoul 2012-02-13 06:21:45