iT邦幫忙

2024 iThome 鐵人賽

DAY 7
1
Python

一些Python可以做的事系列 第 7

[Python] ThreadPoolExecutor

  • 分享至 

  • xImage
  •  

ThreadPoolExecutor 是 Python 標準庫 concurrent.futures 中的一個類,它提供了一種便捷的方法來使用 thread pool,從而實現任務的並發執行。使用 ThreadPoolExecutor 可以避免手動管理 thread 的複雜性,同時能夠利用現代 CPU 的多核心能力,提高程序的執行效率。

ThreadPoolExecutor 會維護一個 thread pool,當有任務提交時,它會分配一個空閒的 thread 來執行這些任務。如果沒有空閒thread可用,任務將會等待,直到有 thread 變得可用。一旦 thread pool 中的所有任務完成後,thread pool 將保持空閒狀態,等待下一批任務的到來。

import concurrent.futures

要使用 concurrent.futures 必須先 import concurrent.futures 模組,或使用 from 的方式,單獨 import 特定的類型

from concurrent.futures import ThreadPoolExecutor

ThreadPoolExecutor

ThreadPoolExecutor 會通過創建多個線程(Threads)來建立多個執行器(Executors),以同時執行和處理多個任務(tasks)。ThreadPoolExecutor 有四個主要參數,其中最常用的是 max_workers

  • max_workers:設定 thread 的數量,預設為 5(每個 CPU 核心可以處理最多 5 個 thread )。數量越多,任務的執行速度可能會越快。若設定為小於或等於 0 的數值,則會引發錯誤。
  • thread_name_prefix: thread 的名稱前綴,預設為空字符串('')。
  • initializer:每個 thread 啟動時調用的初始化函數,預設為 None。
  • initargs:傳遞給初始化函數的參數,使用元組(tuple)表示,預設為空元組(())。
from concurrent.futures import ThreadPoolExecutor
 
# 設定一個執行 Thread 的啟動器
# max_workers : 指定 Thread 的數量 ( 預設為 5 個 )
executor = ThreadPoolExecutor(max_workers=3)

使用 ThreadPoolExecutor 後,可以利用其提供的各種方法來管理和執行任務:

  • submit(fn, *args, **kwargs):執行指定的函式 fn,可以傳遞可變參數 *args 和關鍵字參數 **kwargs。此方法會立即返回一個 Future 物件,用於跟蹤任務的執行狀態。
  • map(func, *iterables):以 map 的方式來執行某個函式 func,並處理提供的可迭代對象 *iterables。此方法會返回一個可迭代的結果,這些結果是 func 函式應用於每個輸入項的結果。
  • shutdown(wait=True):在所有任務完成後,關閉 thread pool 並釋放所使用的資源。wait 參數控制方法的行為:
    • 如果 wait 設為 True(預設值),方法會等到所有任務完成後才回傳。
    • 如果 wait 設為 False,方法會立即回傳,而不等待所有任務完成。
import time
from concurrent.futures import ThreadPoolExecutor

def test(n): 
    for i in range(n):
        print(i, end=' ')
        time.sleep(0.1)

with ThreadPoolExecutor() as executor :  # 設定一個執行 Thread 的啟動器
    a = executor.submit(test, 2)         # 啟動第一個 test 函式 ,0 1
    b = executor.submit(test, 3)         # 啟動第二個 test 函式 ,0 1 2
    c = executor.submit(test, 4)         # 啟動第三個 test 函式 ,0 1 2 3
    
    # 也可以改用 map 的做法
    # executor.map(test, [2,3,4])
    
executor.shutdown()                      # 關閉啟動器 ( 如果沒有使用,則啟動器會處在鎖住的狀態而無法繼續 )


# 輸出 : 0 0 0 1 1 1 2 2 3

ThreadPoolExecutor 的優點

  1. 減少系統資源消耗 : 不用一直重複創建與銷毀 thread
  2. 提高響應速度 : 因為一直存在所以減少創建的時間,提高速度
  3. 提高thread的可管理性
    • thread數量控制:thread pool 允許設定 thread 的最大數量,從而避免了系統因過多 thread 而導致的資源競爭和性能下降。
    • 監控和管理:thread pool 通常提供了監控 thread 狀態、獲取thread pool 運行統計訊息等功能,這些都可以更好地管理 thread pool 性能。

參考資料 :
https://steam.oxxostudio.tw/category/python/library/concurrent-futures.html
https://blog.csdn.net/diana_jiuri1314/article/details/131783433


上一篇
[Python] Socket + Threading
下一篇
[Python] Requests
系列文
一些Python可以做的事19
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Penut Chen
iT邦新手 1 級 ‧ 2024-08-16 11:22:10

ThreadPoolExecutor 好像一樣受到 GIL 的限制?

https://stackoverflow.com/a/14991752/26476954

我剛剛查好像是的,ThreadPoolExecuto一樣會受到GIL的限制,我會做更改的,謝謝/images/emoticon/emoticon41.gif

我要留言

立即登入留言