118. Concurrency with concurrent.futures

Here are 10 Python snippets that demonstrate concurrency using the concurrent.futures module with ThreadPoolExecutor and ProcessPoolExecutor.


1. Using ThreadPoolExecutor for Basic Task Execution

from concurrent.futures import ThreadPoolExecutor

def task(n):
    return f"Task {n} completed."

with ThreadPoolExecutor(max_workers=3) as executor:
    results = list(executor.map(task, range(5)))

print(results)

2. Using ProcessPoolExecutor for CPU-Intensive Tasks

from concurrent.futures import ProcessPoolExecutor
import math

def compute_factorial(n):
    return math.factorial(n)

with ProcessPoolExecutor(max_workers=3) as executor:
    results = list(executor.map(compute_factorial, [5, 10, 15, 20]))

print(results)

3. Submitting Tasks Individually


4. Using as_completed to Process Results as They Finish


5. Handling Exceptions in Concurrent Tasks


6. Cancelling Pending Tasks


7. Using ProcessPoolExecutor for Parallel File I/O


8. Mixing ThreadPoolExecutor with I/O Bound Tasks


9. Timing Concurrent Tasks


10. Using ProcessPoolExecutor for Large Dataset Processing


These snippets demonstrate the power and versatility of concurrent.futures for handling concurrency in both I/O-bound tasks (using ThreadPoolExecutor) and CPU-bound tasks (using ProcessPoolExecutor).

Last updated