threadpool_executor_example.py
· 430 B · Python
原始文件
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def task(n):
"""模擬一個耗時任務"""
time.sleep(n)
return f"Task {n} completed after {n} seconds"
# 建立執行緒池
with ThreadPoolExecutor(max_workers=3) as executor:
futures = {executor.submit(task, i): i for i in range(1, 4)}
for future in as_completed(futures):
result = future.result()
print(result)
| 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) |
| 16 |