2014-11-09 77 views
0

我一直對Python的多重處理感到震驚,因爲我現在已經做得很好,我已經設法取得了很小的進展 - 我很抱歉如果我的問題是重複的或我的無知是明顯的 - 我不能用這種方式在其他地方發現它。多處理和可變返回?

我正在尋找一種方式來並行運行功能,並返回一些他們已經產生的任意東西回到主腳本。

問題是:一個Process()從Multiprocessing開始可以返回一個列表或其他任意變量類型嗎?

例如,我想:

def 30_second_function(): 
    #pretend this takes 30 seconds to run 
    return ["mango", "habanero", "salsa"] 
#End 30_second_function() 

def 5_second_function(): 
    #pretend this takes 5 seconds to run 
    return {"beans": "8 oz", "tomato paste": "16 oz"} 
#End 5_second_function() 

p1 = multiprocessing.Process(target=30_second_function) 
p1.start() 
p2 = multiprocessing.Process(target=5_second_function) 
p2.start() 

#Somehow retrieve the list and the dictionary here. p1.returned?? 

然後以某種方式訪問​​從30_second_function列表,並從5_second_function字典。這可能嗎?我是否以這種錯誤的方式去做?

回答

3

Process本身並不提供獲取返回值的方法。 To exchange data between processes, you need to use queue, pipe,共享內存,...:

import multiprocessing 

def thirty_second_function(q): 
    q.put(["mango", "habanero", "salsa"]) 

def five_second_function(q): 
    q.put({"beans": "8 oz", "tomato paste": "16 oz"}) 

if __name__ == '__main__': 
    q1 = multiprocessing.Queue() 
    p1 = multiprocessing.Process(target=thirty_second_function, args=(q1,)) 
    p1.start() 

    q2 = multiprocessing.Queue() 
    p2 = multiprocessing.Process(target=five_second_function, args=(q2,)) 
    p2.start() 

    print(q1.get()) 
    print(q2.get()) 

替代使用multiprocessing.pool.Pool

import multiprocessing.pool 

def thirty_second_function(): 
    return ["mango", "habanero", "salsa"] 

def five_second_function(): 
    return {"beans": "8 oz", "tomato paste": "16 oz"} 

if __name__ == '__main__': 
    p = multiprocessing.pool.Pool() 
    p1 = p.apply_async(thirty_second_function) 
    p2 = p.apply_async(five_second_function) 

    print(p1.get()) 
    print(p2.get()) 

或者使用concurrent.futures modulealso available in standard library since Python 3.2+):

from concurrent.futures import ProcessPoolExecutor 

def thirty_second_function(): 
    return ["mango", "habanero", "salsa"] 

def five_second_function(): 
    return {"beans": "8 oz", "tomato paste": "16 oz"} 

if __name__ == '__main__': 
    with ProcessPoolExecutor() as e: 
     p1 = e.submit(thirty_second_function) 
     p2 = e.submit(five_second_function) 
    print(p1.result()) 
    print(p2.result()) 
+0

這正是我需要的 - 我不知道爲什麼我沒有從文檔中理解這一點,但你的例子在這裏確實有幫助。我迫不及待地嘗試。 偏題 - 你知道爲什麼args =(q1,)需要看似無賴的逗號才能正常工作嗎? – Locane 2014-11-09 03:51:38

+1

@Locane,沒有尾隨的逗號,它是''(q1)',它等於'q1'。你可以使用列表形式:'[q1]'如果你不喜歡它。 – falsetru 2014-11-09 03:53:31

+1

@Locane,你說得對。尾隨逗號表示它是一個元組文字。順便說一句,它也接受一個列表。 – falsetru 2014-11-09 03:56:52