Python 的 ProcessPoolExecutor 類


Python 中的 ProcessPoolExecutor 類是 concurrent.futures 模組的一部分,它是一個高階介面,用於使用程序和執行緒非同步執行函式。ProcessPoolExecutor 允許我們使用多個程序並行執行多個函式,這對於受益於並行化過程的 CPU 密集型任務尤其有用。

多程序和多執行緒

在瞭解 ProcessPoolExecutor 類之前,我們必須瞭解多程序和多執行緒。多程序和多執行緒是用於實現並行化過程的技術,它們在管理和建立併發任務的方式上有所不同。

多程序使用多個程序來並行執行任務,每個程序都有自己的記憶體空間,以避免共享記憶體和併發問題。它也是程序間通訊的一種方式,這可能更復雜且成本更高,因為資料必須在程序之間進行序列化和反序列化。多程序尤其用於 CPU 密集型任務,這些任務受益於執行並行化任務,例如數值計算或影像處理等。在 Python 中,我們有一個名為 multiprocessing 的模組,它允許我們建立和管理程序,而 pool 類用於管理工作程序池以並行執行函式。

多執行緒在一個程序中使用多個執行緒來實現並行化,每個執行緒與主執行緒共享相同的記憶體空間,這可以簡化執行緒間的通訊。這意味著我們在訪問共享資料時需要小心,以避免併發問題,例如競爭條件或死鎖。多執行緒用於執行 I/O 密集型任務,這些任務受益於並行化,例如網路程式設計或檔案處理等。在 Python 中,我們有 threading 模組來建立和管理執行緒,thread 類用於建立新執行緒並在該執行緒中執行函式。lock 類用於同步執行緒之間對共享資料的訪問。

建立 ProcessPoolExecutor

建立 ProcessPoolExecutor 的過程類似於 ThreadPoolExecutor,唯一的區別是我們必須從 concurrent.futures 模組匯入該類。我們將使用 OS 模組獲取當前在我們的池中執行的任務 PID。

示例

from concurrent.futures import ProcessPoolExecutor
import os
def task():
   print("Current executing task PID {}".format(os.getpid()))
if __name__ == '__main__':
   result =[]
   with ProcessPoolExecutor(max_workers=3) as exe:
      result1 = exe.submit(task())

輸出

Current executing task PID 6652

示例

from concurrent.futures import ProcessPoolExecutor
import os
values = [10,40,30,4]
def square(x):
   print(f'square of {x}:{x*x}')
   print("Current executing task PID {}".format(os.getpid()))
if __name__ == '__main__':
   result =[]
   with ProcessPoolExecutor(max_workers = 5) as exe:
      for i in values:
         result = exe.submit(square(i))

輸出

square of 10:100
Current executing task PID 19276
square of 40:1600
Current executing task PID 19276
square of 30:900
Current executing task PID 19276
square of 4:16
Current executing task PID 19276

更新於:2023年10月19日

116 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.