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¶
- class
concurrent.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 as
fn(*args**kwargs)and returns aFutureobject 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)¶Equivalent to
map(func,*iterables)exceptfunc is executedasynchronously and several calls tofunc may be made concurrently. Thereturned 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 a call raises anexception, then that exception will be raised when its value isretrieved from the iterator. When usingProcessPoolExecutor, thismethod chopsiterables into a number of chunks which it submits to thepool as separate tasks. The (approximate) size of these chunks can bespecified by settingchunksize to a positive integer. For very longiterables, 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 to
Executor.submit()andExecutor.map()made after shutdown willraiseRuntimeError.Ifwait is
Truethen this method will not return until all thepending futures are done executing and the resources associated with theexecutor have been freed. Ifwait isFalsethen 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 the
withstatement, 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)
- class
concurrent.futures.ThreadPoolExecutor(max_workers=None)¶ An
Executorsubclass that uses a pool of at mostmax_workersthreads to execute calls asynchronously.Changed in version 3.5:Ifmax_workers is
Noneornot given, it will default to the number of processors on the machine,multiplied by5, assuming thatThreadPoolExecutoris oftenused to overlap I/O instead of CPU work and the number of workersshould be higher than the number of workersforProcessPoolExecutor.
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.
- class
concurrent.futures.ProcessPoolExecutor(max_workers=None)¶ An
Executorsubclass that executes calls asynchronously using a poolof at mostmax_workers processes. Ifmax_workers isNoneor 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, a
BrokenProcessPoolerror 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().
- class
concurrent.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 return
False, otherwise thecall will be cancelled and the method will returnTrue.
cancelled()¶Return
Trueif the call was successfully cancelled.
running()¶Return
Trueif the call is currently being executed and cannot becancelled.
done()¶Return
Trueif 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 a
concurrent.futures.TimeoutErrorwill 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 then
CancelledErrorwill 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 a
concurrent.futures.TimeoutErrorwill 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 then
CancelledErrorwill be raised.If the call completed without raising,
Noneis 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 an
Exceptionsubclass, it will be logged andignored. If the callable raises aBaseExceptionsubclass, thebehavior is undefined.If the future has already completed or been cancelled,fn will becalled immediately.
The following
Futuremethods are meant for use in unit tests andExecutorimplementations.set_running_or_notify_cancel()¶This method should only be called by
Executorimplementationsbefore executing the work associated with theFutureand by unittests.If the method returns
Falsethen theFuturewas cancelled,i.e.Future.cancel()was called and returnedTrue. Any threadswaiting on theFuturecompleting (i.e. throughas_completed()orwait()) will be woken up.If the method returns
Truethen theFuturewas 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 after
Future.set_result()orFuture.set_exception()have beencalled.
17.4.5. Module Functions¶
concurrent.futures.wait(fs,timeout=None,return_when=ALL_COMPLETED)¶Wait for the
Futureinstances (possibly created by differentExecutorinstances) 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 specifiedor
None, 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_COMPLETEDThe function will return when anyfuture finishes or is cancelled. FIRST_EXCEPTIONThe function will return when anyfuture finishes by raising anexception. If no future raises anexception then it is equivalent to ALL_COMPLETED.ALL_COMPLETEDThe function will return when allfutures finish or are cancelled.
concurrent.futures.as_completed(fs,timeout=None)¶Returns an iterator over the
Futureinstances (possibly created bydifferentExecutorinstances) 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.TimeoutErrorif__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¶
- exception
concurrent.futures.CancelledError¶ Raised when a future is cancelled.
- 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 whenone of the workers of aProcessPoolExecutorhas terminatedin a non-clean fashion (for example, if it was killed from the outside).New in version 3.3.
