Multiprocessing.Pool

在詢問如何在 Python 中使用執行緒時,簡單的答案是:“不要。使用程序,而不是。” 多處理模組允許你建立具有與建立執行緒類似的語法的程序,但我更喜歡使用它們方便的 Pool 物件。

使用 David Beazley 首先用於顯示執行緒對 GIL 的危險的程式碼 ,我們將使用 multiprocessing.Pool重寫它 :

David Beazley 的程式碼顯示了 GIL 執行緒問題

from threading import Thread
import time
def countdown(n):
    while n > 0:
        n -= 1

COUNT = 10000000

t1 = Thread(target=countdown,args=(COUNT/2,))
t2 = Thread(target=countdown,args=(COUNT/2,))
start = time.time()
t1.start();t2.start()
t1.join();t2.join()
end = time.time()
print end-start

使用 multiprocessing.Pool 重寫:

import multiprocessing
import time
def countdown(n):
    while n > 0:
        n -= 1

COUNT = 10000000

start = time.time()
with multiprocessing.Pool as pool:
    pool.map(countdown, [COUNT/2, COUNT/2])

    pool.close()
    pool.join()

end = time.time()
print(end-start)

這不會建立執行緒,而是建立新流程。由於每個程序都是自己的直譯器,因此沒有 GIL 衝突。multiprocessing.Pool 將開啟與機器上的核心一樣多的程序,但在上面的示例中,它只需要兩個。在實際場景中,你希望將列表設計為至少與計算機上的處理器一樣長。池將執行你告訴它與每個引數一起執行的函式,直到它建立的程序數。函式完成後,列表中的任何剩餘函式都將在該程序上執行。

我發現,即使使用 with 語句,如果不關閉並加入池,程序仍然存在。為了清理資源,我總是關閉並加入我的池。