最終更新 9 months ago

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

timmy revised this gist 9 months ago. Go to revision

1 file changed, 15 insertions

threadpool_executor_example.py(file created)

@@ -0,0 +1,15 @@
1 + from concurrent.futures import ThreadPoolExecutor, as_completed
2 + import time
3 +
4 + def task(n):
5 + """模擬一個耗時任務"""
6 + time.sleep(n)
7 + return f"Task {n} completed after {n} seconds"
8 +
9 + # 建立執行緒池
10 + with 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)
Newer Older