SuperFastPython.
com Cheat Sheet for ProcessPoolExecutor
Why ProcessPoolExecutor? Issue Async Tasks to the Pool Use Futures (handles on async tasks)
Execute ad hoc functions that perform CPU-bound
tasks asynchronously in new child processes, such Issue one task asynchronously Get result (blocking)
as compute tasks or mathematical operations. future = [Link](task) result = [Link]()
Create, Configure, Use Issue one task with arguments Get result with exception
future = [Link](task, a1, a2) try:
Imports result = [Link]()
from [Link] import * Issue many tasks, collect Futures except Exception as e:
futures = [[Link](task) for _ # ...
Create, default config in range(5)]
pool = ProcessPoolExecutor() Get result with timeout in seconds
Issue many tasks, iterate results in order try:
Config number of workers for res in [Link](task, res = [Link](timeout=0.5)
pool = range(10)): except TimeoutError as e:
ProcessPoolExecutor(max_workers=10) # ... # ...
Config multiprocessing context Issue many tasks, iterate results with timeout Get an exception
ctx = try: exception = [Link]()
multiprocessing.get_context(‘spawn’) for r in [Link](task,
pool = range(10), timeout=0.5): Get exception with timeout in seconds
ProcessPoolExecutor(mp_context=ctx) # ... try:
except TimeoutError as e: e =
Config worker initializer function # ... [Link](timeout=0.5)
pool = except TimeoutError as toe:
ProcessPoolExecutor(initializer=init Issue many tasks in chunks, iterate results # ...
, initargs=(a1, a2)) for res in [Link](task, range(10),
chunksize=10): Cancel a running task
Shutdown and wait, not cancel tasks # ... cancelled = [Link]()
[Link]()
Wait for all tasks via futures Check if task is running (not done)
Shutdown no wait, not cancel tasks wait(futures) if [Link]():
[Link](wait=False) # ...
Wait with a timeout in seconds
Shutdown and wait, cancel tasks wait(futures, timeout=0.5) Check if task done (not running)
[Link](cancel_futures=True) if [Link]():
Wait for first task # ...
Shutdown no wait, cancel tasks wait(futures, FIRST_COMPLETED)
[Link](wait=False, Check if task cancelled
cancel_futures=True) Wait for for first task failure if [Link]():
wait(futures, FIRST_EXCEPTION) # ...
Context manager, shutdown automatically
with ProcessPoolExecutor() as e: Iterate futures in order completed Add a task done callback
# ... for fut in as_completed(futures): future.add_done_callback(myfunc)
# ...