futures Package¶
futures
Package¶
Execute computations asynchronously using threads or processes.
_base
Module¶
-
exception
leo.external.concurrent.futures._base.
CancelledError
[source]¶ Bases:
leo.external.concurrent.futures._base.Error
The Future was cancelled.
-
class
leo.external.concurrent.futures._base.
DoneAndNotDoneFutures
(done, not_done)¶ Bases:
tuple
-
done
¶ Alias for field number 0
-
not_done
¶ Alias for field number 1
-
-
exception
leo.external.concurrent.futures._base.
Error
[source]¶ Bases:
exceptions.Exception
Base class for all future-related exceptions.
-
class
leo.external.concurrent.futures._base.
Executor
[source]¶ Bases:
object
This is an abstract base class for concrete asynchronous executors.
-
map
(fn, *iterables, **kwargs)[source]¶ Returns a iterator equivalent to map(fn, iter).
- Args:
- fn: A callable that will take take as many arguments as there are
- passed iterables.
- timeout: The maximum number of seconds to wait. If None, then there
- is no limit on the wait time.
- Returns:
- An iterator equivalent to: map(func, *iterables) but the calls may be evaluated out-of-order.
- Raises:
- TimeoutError: If the entire result iterator could not be generated
- before the given timeout.
Exception: If fn(*args) raises for any values.
-
shutdown
(wait=True)[source]¶ Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Args:
- wait: If True then shutdown will not return until all running
- futures have finished executing and the resources used by the executor have been reclaimed.
-
-
class
leo.external.concurrent.futures._base.
Future
[source]¶ Bases:
object
Represents the result of an asynchronous computation.
-
add_done_callback
(fn)[source]¶ Attaches a callable that will be called when the future finishes.
- Args:
- fn: A callable that will be called with this future as its only
- argument when the future completes or is cancelled. The callable will always be called by a thread in the same process in which it was added. If the future has already completed or been cancelled then the callable will be called immediately. These callables are called in the order that they were added.
-
cancel
()[source]¶ Cancel the future if possible.
Returns True if the future was cancelled, False otherwise. A future cannot be cancelled if it is running or has already completed.
-
exception
(timeout=None)[source]¶ Return the exception raised by the call that the future represents.
- Args:
- timeout: The number of seconds to wait for the exception if the
- future isn’t done. If None, then there is no limit on the wait time.
- Returns:
- The exception raised by the call that the future represents or None if the call completed without raising.
- Raises:
CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given
timeout.
-
result
(timeout=None)[source]¶ Return the result of the call that the future represents.
- Args:
- timeout: The number of seconds to wait for the result if the future
- isn’t done. If None, then there is no limit on the wait time.
- Returns:
- The result of the call that the future represents.
- Raises:
CancelledError: If the future was cancelled. TimeoutError: If the future didn’t finish executing before the given
timeout.Exception: If the call raised then that exception will be raised.
-
set_exception
(exception)[source]¶ Sets the result of the future as being the given exception.
Should only be used by Executor implementations and unit tests.
-
set_result
(result)[source]¶ Sets the return value of work associated with the future.
Should only be used by Executor implementations and unit tests.
-
set_running_or_notify_cancel
()[source]¶ Mark the future as running or process any cancel notifications.
Should only be used by Executor implementations and unit tests.
If the future has been cancelled (cancel() was called and returned True) then any threads waiting on the future completing (though calls to as_completed() or wait()) are notified and False is returned.
If the future was not cancelled then it is put in the running state (future calls to running() will return True) and True is returned.
This method should be called by Executor implementations before executing the work associated with this future. If this method returns False then the work should not be executed.
- Returns:
- False if the Future was cancelled, True otherwise.
- Raises:
- RuntimeError: if this method was already called or if set_result()
- or set_exception() was called.
-
-
exception
leo.external.concurrent.futures._base.
TimeoutError
[source]¶ Bases:
leo.external.concurrent.futures._base.Error
The operation exceeded the given deadline.
-
leo.external.concurrent.futures._base.
as_completed
(fs, timeout=None)[source]¶ An iterator over the given futures that yields each as it completes.
- Args:
- fs: The sequence of Futures (possibly created by different Executors) to
- iterate over.
- timeout: The maximum number of seconds to wait. If None, then there
- is no limit on the wait time.
- Returns:
- An iterator that yields the given Futures as they complete (finished or cancelled).
- Raises:
- TimeoutError: If the entire result iterator could not be generated
- before the given timeout.
-
leo.external.concurrent.futures._base.
wait
(fs, timeout=None, return_when='ALL_COMPLETED')[source]¶ Wait for the futures in the given sequence to complete.
- Args:
- fs: The sequence of Futures (possibly created by different Executors) to
- wait upon.
- timeout: The maximum number of seconds to wait. If None, then there
- is no limit on the wait time.
- return_when: Indicates when this function should return. The options
are:
- FIRST_COMPLETED - Return when any future finishes or is
- cancelled.
- FIRST_EXCEPTION - Return when any future finishes by raising an
- exception. If no future raises an exception then it is equivalent to ALL_COMPLETED.
ALL_COMPLETED - Return when all futures finish or are cancelled.
- Returns:
- A named 2-tuple of sets. The first set, named ‘done’, contains the futures that completed (is finished or cancelled) before the wait completed. The second set, named ‘not_done’, contains uncompleted futures.
_compat
Module¶
-
leo.external.concurrent.futures._compat.
namedtuple
(typename, field_names)[source]¶ Returns a new subclass of tuple with named fields.
>>> Point = namedtuple('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessable by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22)
process
Module¶
Implements ProcessPoolExecutor.
The follow diagram and text describe the data-flow through the system:
|======================= In-process =====================|== Out-of-process ==|
+———-+ +———-+ +——–+ +———–+ +———+ | | => | Work Ids | => | | => | Call Q | => | | | | +———-+ | | +———–+ | | | | | … | | | | … | | | | | | 6 | | | | 5, call() | | | | | | 7 | | | | … | | | | Process | | … | | Local | +———–+ | Process | | Pool | +———-+ | Worker | | #1..n | | Executor | | Thread | | | | | +———– + | | +———–+ | | | | <=> | Work Items | <=> | | <= | Result Q | <= | | | | +————+ | | +———–+ | | | | | 6: call() | | | | … | | | | | | future | | | | 4, result | | | | | | … | | | | 3, except | | | +———-+ +————+ +——–+ +———–+ +———+
Executor.submit() called: - creates a uniquely numbered _WorkItem and adds it to the “Work Items” dict - adds the id of the _WorkItem to the “Work Ids” queue
Local worker thread: - reads work ids from the “Work Ids” queue and looks up the corresponding
WorkItem from the “Work Items” dict: if the work item has been cancelled then it is simply removed from the dict, otherwise it is repackaged as a _CallItem and put in the “Call Q”. New _CallItems are put in the “Call Q” until “Call Q” is full. NOTE: the size of the “Call Q” is kept small because calls placed in the “Call Q” can no longer be cancelled with Future.cancel().
- reads _ResultItems from “Result Q”, updates the future stored in the “Work Items” dict and deletes the dict entry
Process #1..n: - reads _CallItems from “Call Q”, executes the calls, and puts the resulting
_ResultItems in “Request Q”
-
class
leo.external.concurrent.futures.process.
ProcessPoolExecutor
(max_workers=None)[source]¶ Bases:
concurrent.futures._base.Executor
-
shutdown
(wait=True)[source]¶ Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Args:
- wait: If True then shutdown will not return until all running
- futures have finished executing and the resources used by the executor have been reclaimed.
-
thread
Module¶
Implements ThreadPoolExecutor.
-
class
leo.external.concurrent.futures.thread.
ThreadPoolExecutor
(max_workers)[source]¶ Bases:
concurrent.futures._base.Executor
-
shutdown
(wait=True)[source]¶ Clean-up the resources associated with the Executor.
It is safe to call this method several times. Otherwise, no other methods can be called after this one.
- Args:
- wait: If True then shutdown will not return until all running
- futures have finished executing and the resources used by the executor have been reclaimed.
-