Python / concurrent.futures

concurrent.futures -- Launching parallel tasks

By Marcelo Fernandes Sep 1, 2017

Concurrency with futures - Launching parallel tasks

This post focuses on the concurrent.futures library that was introduced back in Python 3.2. It makes very trivial to launch concurrent threads and processes, creating a high-level interface for asynchronously executing callables.

In the biggest majority of cases, one only needs to know how to spawn a bunch of independent threads and collect their results in a queue. This is sort of the spirit that concurrent.futures provides for the user, it makes it very easy to perform threads and process through the api.



Executor Objects, the interface for running concurrent.futures

The Executor abstract class is the one that provides methods to execute calls asynchronously. It should not be used directly, but through its concrete subclasses: ThreadPoolExecutor and ProcessPoolExecutor

submit(fn, *args, **kwargs)

Schedules the callable, fn, to be executed as fn(*args, **kwargs) and returns a Future object, representing the execution of the callable.


from concurrent.futures import ThreadPoolExecutor

def pow(x, y):
    return x**y

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 10, 5)
    print(future.result())

# 100000

future
# <Future at 0x7fc2e9b1b6d8 state=finished returned int>

dir(future)
# ['_Future__get_result', '__class__', '__delattr__', '__dict__',
# '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
# '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__',
# '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
# '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__',
# '_condition', '_done_callbacks', '_exception', '_invoke_callbacks', '_result',
# '_state', '_waiters', 'add_done_callback', 'cancel', 'cancelled', 'done', 'exception',
# 'result', 'running', 'set_exception', 'set_result', 'set_running_or_notify_cancel']

map(func, *iterables, timeout=None, chunksize=1)

Equivalent to the map(func, *iterables) except func is executed asynchronously and serveral calls to func may be made concurrently. The returned iterator raises a concurrent.futures.TimeoutError if __next__() is called and the result is not available after timeout seconds from the original call to Executor.map(). timeout can be an int or a float. If timeout is None, there is no limit to the wait time. If a call raises an exception, then that exception will be raised only 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. For very long iterables, using a large value of chunksize can significantly improve performance compared to the default size of 1. With ThreadPoolExecutor, chunksize has no effect.


with ThreadPoolExecutor(max_workers=1) as executor:
    futures = executor.map(pow, [10, 5], [3, 3])

for future in futures:
    print(future)

# 100
# 125

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() and Executor.map() made after shutdown will raise RuntimeError

If wait is True, then this method will not return until all the pending futures are done executing and the resources associeated with the executor have been freed. If wait is False, then 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. This method might be useful when launching daemon threads.

You can avoid to call this method explicitly if you use the with statement, because the __exit__ method of the Executor, will call it for you. We can see it from the library source code for executor:


class Executor(object):

    # some other methods before those and finally:


    def shutdown(self, wait=True):
        # This method is to be implemented on the concrete classes.
        pass

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.shutdown(wait=True)
        return False



ThreadPoolExecutor(max_workers=None, thread_name_prefix=")

This class is a concrete class implementation of Executor, that uses pool of threads to execute calls asynchronously.

You should take care about some details. For example, Deadlocks can occur when the callable associated with Future waits on the results of another Future. For example:


import time

def wait_on_b():
    time.sleep(5)
    print(b.result())  # b will never complete because it is waiting on a.
    return 5

def wait_on_a():
    time.sleep(5)
    print(a.result())  # a will never complete because it is waiting on b.
    return 6


executor = ThreadPoolExecutor(max_workers=2)
a = executor.submit(wait_on_b)
b = executor.submit(wait_on_a)

And


def wait_on_future():
    f = executor.submit(pow, 5, 2)
    # This will never complete because there is only one worker thread and
    # it is executing this function.
    print(f.result())

executor = ThreadPoolExecutor(max_workers=1)
executor.submit(wait_on_future)

ProcessPoolExecutor(max_workers=None)

The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor uses the multiprocessing module, which allows it to side-step the Global Interpreter Lock but also means that only picklable objects can be executed and returned.

The __main__ module must be importable by worker subprocesses. This means that ProcessPoolExecutor will not work in the interactive interpreter.

An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is lower or equal to 0, then a ValueError will be raised.


import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()



Future Objects

The Future class encapsulates the asynchronous execution of a callable. Future instances are created by Executor.submit() and should not be created directly except for testing.

cancel()

Attempt to cancel the call. If the call is currently being executed and cannot be cancelled then the method will return False, otherwise the call will be cancelled and the method will return True.

cancelled()

Return True if the call was successfully cancelled.

running()

Return True if the call is currently being executed and cannot be cancelled.

done()

Return True if the call was successfully cancelled or finished running.

result(timeout=None)

Return the value returned by the call. If the call hasn't yet completed, then this method will wait up to timeout seconds. If the call hasn't completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time.

If the future is cancelled before completing then CancelledError will be raised.

If the call raised, this method will raise the same exception.

exception(timeout=None)

Return the exception raised by the call. If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time.

If the future is cancelled before completing then CancelledError will be raised.

If the call completed without raising, None is returned.

add_done_callback(fn)

Attaches the callable fn to the future. fn will be called, with the future as its only argument, when the future is cancelled or finishes running.

Added callables are called in the order that they were added and are always called in a thread belonging to the process that added them. If the callable raises an Exception subclass, it will be logged and ignored. If the callable raises a BaseException subclass, the behavior is undefined.


Notes


References

Link 1