import concurrent.futuresdefsquare(x):return x **2# processing on the resultdefprocess_result(future): result = future.result()print(result)# Create worker threadswith concurrent.futures.ThreadPoolExecutor(max_workers=2)as executor: task1 = executor.submit(square, 5) task1.add_done_callback(process_result) task2 = executor.submit(square, 7) task2.add_done_callback(process_result)
running()
檢查任務是否正在執行且無法取消。
PYTHON
import timeimport concurrent.futuresdeftask(): time.sleep(1)print("Task executed.")with concurrent.futures.ThreadPoolExecutor()as executor: future = executor.submit(task)if future.running():# Check taskprint("Task is currently running.")# ✔️✔️else:print("Task is not running.")
PYTHON
import concurrent.futuresimport timedeftask(index):print(f"Task {index} executed.") time.sleep(1.5)executor = concurrent.futures.ThreadPoolExecutor()# Submit tasksfutures = []for i inrange(5): future = executor.submit(task, i) futures.append(future)# Monitor running statuswhileany(f.running() for f in futures):print("Tasks are still running...") time.sleep(0.3)print("All tasks have completed.")executor.shutdown()
執行結果:
Task 0 executed.
Task 1 executed.
Task 2 executed.
Task 3 executed.
Task 4 executed.
Tasks are still running...
Tasks are still running...
Tasks are still running...
Tasks are still running...
Tasks are still running...
Tasks are still running...
Tasks are still running...
Tasks are still running...
All tasks have completed.
cancel()
嘗試取消任務。如果調用當前正在執行的任務或已完成的任務,則該方法將返回 False。
PYTHON
import timeimport concurrent.futuresdeftask(): time.sleep(1)print("Task executed.")with concurrent.futures.ThreadPoolExecutor()as executor: future = executor.submit(task)if future.cancel():print("Task cancelled.")else:print("Task could not be cancelled.")# ✔️✔️
cancelled()
檢查任務是否已被取消。
PYTHON
import timeimport concurrent.futuresdeftask(): time.sleep(1)print("Task executed.")with concurrent.futures.ThreadPoolExecutor()as executor: future = executor.submit(task) future.cancel()if future.cancelled():# Check taskprint("Task cancelled.")else:print("Task could not be cancelled.")# ✔️✔️
exception()
返回調用任務所引發的 exception。
PYTHON
from concurrent import futuresdeftask():raiseValueError("Something went wrong!")# Create worker threadswith futures.ThreadPoolExecutor(max_workers=5)as executor:# Submit tasks future = executor.submit(task) result = future.exception()print(result)# Output: Something went wrong!
import timeimport concurrent.futuresdefsome_task(n): time.sleep(1)return n *2# Create worker threadswith concurrent.futures.ThreadPoolExecutor(max_workers=3)as executor:# Submit tasks futures = [executor.submit(some_task, i)for i inrange(5)]# Use as_completed()for future in concurrent.futures.as_completed(futures): result = future.result()print(f"Task result: {result}")# No use as_completed()for future in futures: result = future.result()print(f"Task result: {result}")