2017-04-06 171 views
0
import multiprocessing 
import requests 

def work(number): 
    link = 'http://APILink/' 
    response = requests.get(link).text 
    print response 

if __name__ == "__main__": 
    number_processes = 2 
    pool = multiprocessing.Pool(number_processes) 
    results = pool.map_async(work, range(1,3)) 
    pool.close() 
    pool.join() 

我在上面的代碼運行使用2進程異步運行多處理。但是當我運行代碼時,它的連續運行卻並不平行。如何同時運行這兩個進程。python多進程異步運行進程一個接一個

+0

你怎麼知道它連續運行?我試過你的代碼 - 它在我的系統上並行運行。 –

+0

當我點擊api鏈接時,我花了4秒,而當我用兩個進程運行腳本時,花了我大約10秒,本身告訴它一個接一個地運行。 –

+0

這可能不是最可靠的方法檢測串行與並行。我建議在worker的開始/結尾處添加一些'print'begin/end worker%d「%number'語句。 –

回答

-1

您需要的工人池,檢查出:從文檔 The docs: using a pool of workers

退房:

from multiprocessing import Pool 
p = Pool(5) 
def f(x): 
    return x*x 

p.map(f, [1,2,3]) 

,你需要你的函數的員工名單中映射。

請注意背景中的惡魔進程。

+0

這幾乎就是線程啓動器所具有的功能,除了線程啓動器使用map_async - 映射的變體作爲文檔狀態。 –