๐ PREMIUM: ./library/concurrent.futures.html - Complete Album!
17.4. concurrent.futures โ Launching parallel tasksยถ
New in version 3.2.
Source code: Lib/concurrent/futures/thread.py and Lib/concurrent/futures/process.py
The concurrent.futures module provides a high-level interface for
asynchronously executing callables.
The asynchronous execution can be performed with threads, using
ThreadPoolExecutor, or separate processes, using
ProcessPoolExecutor. Both implement the same interface, which is
defined by the abstract Executor class.
17.4.1. Executor Objectsยถ
-
class
concurrent.futures.Executorยถ An abstract class that provides methods to execute calls asynchronously. It should not be used directly, but through its concrete subclasses.
-
submit(fn, *args, **kwargs)ยถ Schedules the callable, fn, to be executed as
fn(*args **kwargs)and returns aFutureobject representing the execution of the callable.with ThreadPoolExecutor(max_workers=1) as executor: future = executor.submit(pow, 323, 1235) print(future.result())
-
map(func, *iterables, timeout=None, chunksize=1)ยถ Similar to
map(func, *iterables)except:the iterables are collected immediately rather than lazily;
func is executed asynchronously and several calls to func may be made concurrently.
The returned iterator raises a
concurrent.futures.TimeoutErrorif__next__()is called and the result isnโt available after timeout seconds from the original call toExecutor.map(). timeout can be an int or a float. If timeout is not specified orNone, there is no limit to the wait time.If a func call raises an exception, then that exception will be raised when its value is retrieved from the iterator.
When using
ProcessPoolExecutor, this method chops iterables into a number of chunks which it submits to the pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer. For very long iterables, using a large value for chunksize can significantly improve performance compared to the default size of 1. WithThreadPoolExecutor, chunksize has no effect.Changed in version 3.5: Added the chunksize argument.
-
shutdown(wait=True)ยถ Signal the executor that it should free any resources that it is using when the currently pending futures are done executing. Calls to
Executor.submit()andExecutor.map()made after shutdown will raiseRuntimeError.If wait is
Truethen this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait isFalsethen this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing.You can avoid having to call this method explicitly if you use the
withstatement, which will shutdown theExecutor(waiting as ifExecutor.shutdown()were called with wait set toTrue):
-
