最后活跃于 9 months ago

ThreadPoolExecutor 提供了一種簡單的方式來管理多執行緒,適用於 I/O 密集型任務(如網路請求、檔案處理、資料庫查詢),提高執行效率。

修订 b633db889ad54830097b88e65f8416767bb7be95

threadpool_executor_example.py 原始文件
1from concurrent.futures import ThreadPoolExecutor, as_completed
2import time
3
4def task(n):
5 """模擬一個耗時任務"""
6 time.sleep(n)
7 return f"Task {n} completed after {n} seconds"
8
9# 建立執行緒池
10with ThreadPoolExecutor(max_workers=3) as executor:
11 futures = {executor.submit(task, i): i for i in range(1, 4)}
12
13 for future in as_completed(futures):
14 result = future.result()
15 print(result)
16