簡體   English   中英

澄清Python的`multiprocessing.Pool`的`processes`參數

[英]Clarification on the `processes` argument for Python's `multiprocessing.Pool`

我的問題是,是否按如下所示對[pool.apply_async(myfunc, args=(y,)) for i in range(8)]執行[pool.apply_async(myfunc, args=(y,)) for i in range(8)] ,並使用多個進程(例如,此處4初始化Pool
這是否意味着每個函數調用都在4個進程上並行運行,我也正在並行運行8個函數調用,所以4x8 = 32個進程,或者它運行4次1次函數調用,等到它們完成然后再運行另一個4個函數調用?

import multiprocessing
pool = multiprocessing.Pool(processes=4)
results = [pool.apply_async(myfunc, args=(i,)) for i in range(8)]
results = [res.get() for res in results]

一個multiprocessing.Pool並行運行的進程數量絕不會超過創建時指定的數量。 相反,它會立即生成您指定數量的進程,並使它們一直運行,直到關閉/加入池為止。 因此,就您而言,即使這些Pool沒有一個正在執行任何工作, Pool也將始終正好運行四個進程。 如果給池提供八個工作項,則前四個將立即開始並行執行,而后四個則進入隊列。 一旦其中一個工作進程完成運行myfunc ,第一個排隊的項目將開始由現在空閑的工作進程處理。

如果運行以下示例,則可以自己查看:

def myfunc(num):
    print("in here %s" % num)
    time.sleep(2)
    print("done with %s" % num)
    return num+2

if __name__ == "__main__":
    pool = multiprocessing.Pool(4)
    results = [pool.apply_async(myfunc, args=(i,)) for i in range(8)]
    results = [res.get() for res in results]
    print results

輸出:

in here 0
in here 1
in here 2
in here 3
<2 second pause>
done with 0
done with 3
done with 1
in here 4
in here 5
in here 6
done with 2
in here 7
<2 second pause>
done with 6
done with 7
done with 4
done with 5
[2, 3, 4, 5, 6, 7, 8, 9]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM