17.4. concurrent.futures — 发起并行任务

3.2 版新增。

源代码: Lib/concurrent/futures/thread.py and Lib/concurrent/futures/process.py


The concurrent.futures 模块为异步执行可调用提供高级接口。

异步执行可以采用线程履行使用 ThreadPoolExecutor ,或单独进程使用 ProcessPoolExecutor 。两者实现相同接口,定义通过抽象 Executor 类。

17.4.1. 执行器对象

class concurrent.futures. Executor

提供异步执行调用的方法的抽象类。不应直接使用它,但应透过它的具体子类。

submit ( fn , *args , **kwargs )

调度可调用 fn 以执行按 fn(*args **kwargs) 并返回 Future 对象表示可调用的执行。

with ThreadPoolExecutor(max_workers=1) as executor:
    future = executor.submit(pow, 323, 1235)
    print(future.result())
						
map ( func , *iterables , timeout=None , chunksize=1 )

相当于 map(func, *iterables) except func 是异步执行的,且多次调用 func may be made concurrently. The returned iterator raises a concurrent.futures.TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to Executor.map() . timeout can be an int or a float. If timeout 未指定或 None , there is no limit to the wait time. If a 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. With ThreadPoolExecutor , chunksize 不起作用。

3.5 版改变: 添加 chunksize 自变量。

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 .

wait is True then 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 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.

You can avoid having to call this method explicitly if you use the with statement, which will shutdown the Executor (waiting as if Executor.shutdown() were called with wait 设为 True ):

import shutil
with ThreadPoolExecutor(max_workers=4) as e:
    e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
    e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
    e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
    e.submit(shutil.copy, 'src4.txt', 'dest4.txt')
						

17.4.2. ThreadPoolExecutor

ThreadPoolExecutor Executor 子类,使用线程池异步执行调用。

死锁会发生当可调用关联 Future waits on the results of another Future 。例如:

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)
					

和:

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)
					
class concurrent.futures. ThreadPoolExecutor ( max_workers=None )

An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously.

3.5 版改变: max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5 , assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor .

17.4.2.1. ThreadPoolExecutor 范例

import concurrent.futures
import urllib.request
URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']
# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()
# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))
					

17.4.3. ProcessPoolExecutor

The ProcessPoolExecutor class is an Executor subclass that uses a pool of processes to execute calls asynchronously. ProcessPoolExecutor 使用 multiprocessing module, which allows it to side-step the 全局解释器锁 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.

调用 Executor or Future methods from a callable submitted to a ProcessPoolExecutor will result in deadlock.

class concurrent.futures. ProcessPoolExecutor ( max_workers=None )

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 会被引发。

3.3 版改变: When one of the worker processes terminates abruptly, a BrokenProcessPool error is now raised. Previously, behaviour was undefined but operations on the executor or its futures would often freeze or deadlock.

17.4.3.1. ProcessPoolExecutor 范例

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()
					

17.4.4. Future 对象

The Future class encapsulates the asynchronous execution of a callable. Future instances are created by Executor.submit() .

class concurrent.futures. Future

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 ( )

返回 True if the call was successfully cancelled.

running ( )

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

done ( )

返回 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 会被引发。 timeout can be an int or float. If timeout 未指定或 None , there is no limit to the wait time.

If the future is cancelled before completing then CancelledError 会被引发。

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 会被引发。 timeout can be an int or float. If timeout 未指定或 None , there is no limit to the wait time.

If the future is cancelled before completing then CancelledError 会被引发。

If the call completed without raising, None 被返回。

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.

If the future has already completed or been cancelled, fn will be called immediately.

下列 Future methods are meant for use in unit tests and Executor implementations.

set_running_or_notify_cancel ( )

This method should only be called by Executor implementations before executing the work associated with the Future and by unit tests.

If the method returns False 那么 Future was cancelled, i.e. Future.cancel() was called and returned True . Any threads waiting on the Future completing (i.e. through as_completed() or wait() ) will be woken up.

If the method returns True 那么 Future was not cancelled and has been put in the running state, i.e. calls to Future.running() 将返回 True .

This method can only be called once and cannot be called after Future.set_result() or Future.set_exception() 有被调用。

set_result ( result )

Sets the result of the work associated with the Future to result .

This method should only be used by Executor implementations and unit tests.

set_exception ( exception )

Sets the result of the work associated with the Future Exception exception .

This method should only be used by Executor implementations and unit tests.

17.4.5. 模块函数

concurrent.futures. wait ( fs , timeout=None , return_when=ALL_COMPLETED )

等待 Future instances (possibly created by different Executor instances) given by fs to complete. Returns a named 2-tuple of sets. The first set, named done , contains the futures that completed (finished or were cancelled) before the wait completed. The second set, named not_done , contains uncompleted futures.

timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout 未指定或 None , there is no limit to the wait time.

return_when indicates when this function should return. It must be one of the following constants:

常量 描述
FIRST_COMPLETED The function will return when any future finishes or is cancelled.
FIRST_EXCEPTION The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED .
ALL_COMPLETED The function will return when all futures finish or are cancelled.
concurrent.futures. as_completed ( fs , timeout=None )

Returns an iterator over the Future instances (possibly created by different Executor instances) given by fs that yields futures as they complete (finished or were cancelled). Any futures given by fs that are duplicated will be returned once. Any futures that completed before as_completed() is called will be yielded first. The returned iterator raises a concurrent.futures.TimeoutError if __next__() is called and the result isn’t available after timeout seconds from the original call to as_completed() . timeout can be an int or float. If timeout 未指定或 None , there is no limit to the wait time.

另请参阅

PEP 3148 – futures - execute computations asynchronously
The proposal which described this feature for inclusion in the Python standard library.

17.4.6. 异常类

exception concurrent.futures. CancelledError

引发当 future 被取消时。

exception concurrent.futures. TimeoutError

Raised when a future operation exceeds the given timeout.

exception concurrent.futures.process. BrokenProcessPool

Derived from RuntimeError , this exception class is raised when one of the workers of a ProcessPoolExecutor has terminated in a non-clean fashion (for example, if it was killed from the outside).

3.3 版新增。