from concurrent.futures import ThreadPoolExecutor def print_message(message): print(message) with ThreadPoolExecutor(max_workers=2) as executor: executor.submit(print_message, "Hello") executor.submit(print_message, "World")
from concurrent.futures import ThreadPoolExecutor def square(number): return number ** 2 with ThreadPoolExecutor(max_workers=2) as executor: numbers = [1, 2, 3, 4, 5] results = executor.map(square, numbers) print(list(results))
from concurrent.futures import ThreadPoolExecutor def divide(numerator, denominator): return numerator / denominator with ThreadPoolExecutor(max_workers=2) as executor: future = executor.submit(divide, 5, 0) try: result = future.result() except ZeroDivisionError: print("Error: division by zero")This example demonstrates how to handle an exception that occurs in a worker thread when dividing by zero. The future.result() call is responsible for blocking until the result is available, at which point it will either return the result or raise an exception that occurred in the worker thread. The try...except block is used to catch and handle the exception in the main thread. In conclusion, concurrent.futures is a package library in Python that allows for easy parallelization of tasks using thread or process-based concurrency. Using the ThreadPoolExecutor class allows for the creation of a pool of worker threads that can be used to execute functions asynchronously.