17.4.concurrent.futures — Launching parallel tasks

New in version 3.2.

Source code:Lib/concurrent/futures/thread.pyandLib/concurrent/futures/process.py


Theconcurrent.futures module provides a high-level interface forasynchronously executing callables.

The asynchronous execution can be performed with threads, usingThreadPoolExecutor, or separate processes, usingProcessPoolExecutor. Both implement the same interface, which isdefined by the abstractExecutor class.

17.4.1.Executor Objects

classconcurrent.futures.Executor

An abstract class that provides methods to execute calls asynchronously. Itshould not be used directly, but through its concrete subclasses.

submit(fn,*args,**kwargs)

Schedules the callable,fn, to be executed asfn(*args**kwargs)and returns aFuture object representing the execution of thecallable.

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

Similar tomap(func,*iterables) except:

  • theiterables are collected immediately rather than lazily;

  • func is executed asynchronously and several calls tofunc may be made concurrently.

The returned iterator raises aconcurrent.futures.TimeoutErrorif__next__() is called and the result isn’t availableaftertimeout seconds from the original call toExecutor.map().timeout can be an int or a float. Iftimeout is not specified orNone, there is no limit to the wait time.

If afunc call raises an exception, then that exception will beraised when its value is retrieved from the iterator.

When usingProcessPoolExecutor, this method chopsiterablesinto a number of chunks which it submits to the pool as separatetasks. The (approximate) size of these chunks can be specified bysettingchunksize to a positive integer. For very long iterables,using a large value forchunksize can significantly improveperformance compared to the default size of 1. WithThreadPoolExecutor,chunksize has no effect.

Changed in version 3.5:Added thechunksize argument.

shutdown(wait=True)

Signal the executor that it should free any resources that it is usingwhen the currently pending futures are done executing. Calls toExecutor.submit() andExecutor.map() made after shutdown willraiseRuntimeError.

Ifwait isTrue then this method will not return until all thepending futures are done executing and the resources associated with theexecutor have been freed. Ifwait isFalse then this method willreturn immediately and the resources associated with the executor will befreed when all pending futures are done executing. Regardless of thevalue ofwait, the entire Python program will not exit until allpending futures are done executing.

You can avoid having to call this method explicitly if you use thewith statement, which will shutdown theExecutor(waiting as ifExecutor.shutdown() were called withwait set toTrue):

importshutilwithThreadPoolExecutor(max_workers=4)ase: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 is anExecutor subclass that uses a pool ofthreads to execute calls asynchronously.

Deadlocks can occur when the callable associated with aFuture waits onthe results of anotherFuture. For example:

importtimedefwait_on_b():time.sleep(5)print(b.result())# b will never complete because it is waiting on a.return5defwait_on_a():time.sleep(5)print(a.result())# a will never complete because it is waiting on b.return6executor=ThreadPoolExecutor(max_workers=2)a=executor.submit(wait_on_b)b=executor.submit(wait_on_a)

And:

defwait_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)
classconcurrent.futures.ThreadPoolExecutor(max_workers=None,thread_name_prefix='')

AnExecutor subclass that uses a pool of at mostmax_workersthreads to execute calls asynchronously.

Changed in version 3.5:Ifmax_workers isNone ornot given, it will default to the number of processors on the machine,multiplied by5, assuming thatThreadPoolExecutor is oftenused to overlap I/O instead of CPU work and the number of workersshould be higher than the number of workersforProcessPoolExecutor.

New in version 3.6:Thethread_name_prefix argument was added to allow users tocontrol thethreading.Thread names for worker threads created bythe pool for easier debugging.

17.4.2.1.ThreadPoolExecutor Example

importconcurrent.futuresimporturllib.requestURLS=['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 contentsdefload_url(url,timeout):withurllib.request.urlopen(url,timeout=timeout)asconn:returnconn.read()# We can use a with statement to ensure threads are cleaned up promptlywithconcurrent.futures.ThreadPoolExecutor(max_workers=5)asexecutor:# Start the load operations and mark each future with its URLfuture_to_url={executor.submit(load_url,url,60):urlforurlinURLS}forfutureinconcurrent.futures.as_completed(future_to_url):url=future_to_url[future]try:data=future.result()exceptExceptionasexc:print('%r generated an exception:%s'%(url,exc))else:print('%r page is%d bytes'%(url,len(data)))

17.4.3.ProcessPoolExecutor

TheProcessPoolExecutor class is anExecutor subclass thatuses a pool of processes to execute calls asynchronously.ProcessPoolExecutor uses themultiprocessing module, whichallows it to side-step theGlobal Interpreter Lock but also means thatonly picklable objects can be executed and returned.

The__main__ module must be importable by worker subprocesses. This meansthatProcessPoolExecutor will not work in the interactive interpreter.

CallingExecutor orFuture methods from a callable submittedto aProcessPoolExecutor will result in deadlock.

classconcurrent.futures.ProcessPoolExecutor(max_workers=None)

AnExecutor subclass that executes calls asynchronously using a poolof at mostmax_workers processes. Ifmax_workers isNone or notgiven, it will default to the number of processors on the machine.Ifmax_workers is lower or equal to0, then aValueErrorwill be raised.

Changed in version 3.3:When one of the worker processes terminates abruptly, aBrokenProcessPool error is now raised. Previously, behaviourwas undefined but operations on the executor or its futures would oftenfreeze or deadlock.

17.4.3.1.ProcessPoolExecutor Example

importconcurrent.futuresimportmathPRIMES=[112272535095293,112582705942171,112272535095293,115280095190773,115797848077099,1099726899285419]defis_prime(n):ifn%2==0:returnFalsesqrt_n=int(math.floor(math.sqrt(n)))foriinrange(3,sqrt_n+1,2):ifn%i==0:returnFalsereturnTruedefmain():withconcurrent.futures.ProcessPoolExecutor()asexecutor:fornumber,primeinzip(PRIMES,executor.map(is_prime,PRIMES)):print('%d is prime:%s'%(number,prime))if__name__=='__main__':main()

17.4.4.Future Objects

TheFuture class encapsulates the asynchronous execution of a callable.Future instances are created byExecutor.submit().

classconcurrent.futures.Future

Encapsulates the asynchronous execution of a callable.Futureinstances are created byExecutor.submit() and should not be createddirectly except for testing.

cancel()

Attempt to cancel the call. If the call is currently being executed andcannot be cancelled then the method will returnFalse, otherwise thecall will be cancelled and the method will returnTrue.

cancelled()

ReturnTrue if the call was successfully cancelled.

running()

ReturnTrue if the call is currently being executed and cannot becancelled.

done()

ReturnTrue if the call was successfully cancelled or finishedrunning.

result(timeout=None)

Return the value returned by the call. If the call hasn’t yet completedthen this method will wait up totimeout seconds. If the call hasn’tcompleted intimeout seconds, then aconcurrent.futures.TimeoutError will be raised.timeout can bean int or float. Iftimeout is not specified orNone, there is nolimit to the wait time.

If the future is cancelled before completing thenCancelledErrorwill 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 yetcompleted then this method will wait up totimeout seconds. If thecall hasn’t completed intimeout seconds, then aconcurrent.futures.TimeoutError will be raised.timeout can bean int or float. Iftimeout is not specified orNone, there is nolimit to the wait time.

If the future is cancelled before completing thenCancelledErrorwill be raised.

If the call completed without raising,None is returned.

add_done_callback(fn)

Attaches the callablefn to the future.fn will be called, with thefuture as its only argument, when the future is cancelled or finishesrunning.

Added callables are called in the order that they were added and arealways called in a thread belonging to the process that added them. Ifthe callable raises anException subclass, it will be logged andignored. If the callable raises aBaseException subclass, thebehavior is undefined.

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

The followingFuture methods are meant for use in unit tests andExecutor implementations.

set_running_or_notify_cancel()

This method should only be called byExecutor implementationsbefore executing the work associated with theFuture and by unittests.

If the method returnsFalse then theFuture was cancelled,i.e.Future.cancel() was called and returnedTrue. Any threadswaiting on theFuture completing (i.e. throughas_completed() orwait()) will be woken up.

If the method returnsTrue then theFuture was not cancelledand has been put in the running state, i.e. calls toFuture.running() will returnTrue.

This method can only be called once and cannot be called afterFuture.set_result() orFuture.set_exception() have beencalled.

set_result(result)

Sets the result of the work associated with theFuture toresult.

This method should only be used byExecutor implementations andunit tests.

set_exception(exception)

Sets the result of the work associated with theFuture to theExceptionexception.

This method should only be used byExecutor implementations andunit tests.

17.4.5.Module Functions

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

Wait for theFuture instances (possibly created by differentExecutor instances) given byfs to complete. Returns a named2-tuple of sets. The first set, nameddone, contains the futures thatcompleted (finished or were cancelled) before the wait completed. The secondset, namednot_done, contains uncompleted futures.

timeout can be used to control the maximum number of seconds to wait beforereturning.timeout can be an int or float. Iftimeout is not specifiedorNone, there is no limit to the wait time.

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

Constant

Description

FIRST_COMPLETED

The function will return when anyfuture finishes or is cancelled.

FIRST_EXCEPTION

The function will return when anyfuture finishes by raising anexception. If no future raises anexception then it is equivalent toALL_COMPLETED.

ALL_COMPLETED

The function will return when allfutures finish or are cancelled.

concurrent.futures.as_completed(fs,timeout=None)

Returns an iterator over theFuture instances (possibly created bydifferentExecutor instances) given byfs that yields futures asthey complete (finished or were cancelled). Any futures given byfs thatare duplicated will be returned once. Any futures that completed beforeas_completed() is called will be yielded first. The returned iteratorraises aconcurrent.futures.TimeoutError if__next__()is called and the result isn’t available aftertimeout seconds from theoriginal call toas_completed().timeout can be an int or float. Iftimeout is not specified orNone, there is no limit to the wait time.

See also

PEP 3148 – futures - execute computations asynchronously

The proposal which described this feature for inclusion in the Pythonstandard library.

17.4.6.Exception classes

exceptionconcurrent.futures.CancelledError

Raised when a future is cancelled.

exceptionconcurrent.futures.TimeoutError

Raised when a future operation exceeds the given timeout.

exceptionconcurrent.futures.process.BrokenProcessPool

Derived fromRuntimeError, this exception class is raised whenone of the workers of aProcessPoolExecutor has terminatedin a non-clean fashion (for example, if it was killed from the outside).

New in version 3.3.