blob: a7a2c394632e983577abdfb5897f9de8e8c0cedd [file] [log] [blame]
Brian Quinlan81c4d362010-09-18 22:35:02 +00001:mod:`concurrent.futures` --- Concurrent computation
2====================================================
3
4.. module:: concurrent.futures
5 :synopsis: Execute computations concurrently using threads or processes.
6
Georg Brandl035cedb2010-09-19 09:31:09 +00007.. versionadded:: 3.2
8
Brian Quinlan81c4d362010-09-18 22:35:02 +00009The :mod:`concurrent.futures` module provides a high-level interface for
10asynchronously executing callables.
11
Benjamin Petersonc713fc72010-09-19 04:23:17 +000012The asynchronous execution can be be performed with threads, using
13:class:`ThreadPoolExecutor`, or seperate processes, using
Georg Brandl035cedb2010-09-19 09:31:09 +000014:class:`ProcessPoolExecutor`. Both implement the same interface, which is
Brian Quinlan81c4d362010-09-18 22:35:02 +000015defined by the abstract :class:`Executor` class.
16
Georg Brandl035cedb2010-09-19 09:31:09 +000017
Brian Quinlan81c4d362010-09-18 22:35:02 +000018Executor Objects
Georg Brandl035cedb2010-09-19 09:31:09 +000019----------------
Brian Quinlan81c4d362010-09-18 22:35:02 +000020
Benjamin Petersonc713fc72010-09-19 04:23:17 +000021.. class:: Executor
Brian Quinlan81c4d362010-09-18 22:35:02 +000022
Georg Brandl035cedb2010-09-19 09:31:09 +000023 An abstract class that provides methods to execute calls asynchronously. It
Benjamin Petersonc713fc72010-09-19 04:23:17 +000024 should not be used directly, but through its concrete subclasses.
Brian Quinlan81c4d362010-09-18 22:35:02 +000025
26 .. method:: submit(fn, *args, **kwargs)
27
Benjamin Petersonc713fc72010-09-19 04:23:17 +000028 Schedules the callable, *fn*, to be executed as ``fn(*args **kwargs)``
29 and returns a :class:`Future` object representing the execution of the
Georg Brandl035cedb2010-09-19 09:31:09 +000030 callable. ::
Brian Quinlan81c4d362010-09-18 22:35:02 +000031
Georg Brandl035cedb2010-09-19 09:31:09 +000032 with ThreadPoolExecutor(max_workers=1) as executor:
33 future = executor.submit(pow, 323, 1235)
34 print(future.result())
Brian Quinlan81c4d362010-09-18 22:35:02 +000035
36 .. method:: map(func, *iterables, timeout=None)
37
Benjamin Petersonc713fc72010-09-19 04:23:17 +000038 Equivalent to ``map(func, *iterables)`` except *func* is executed
Georg Brandl035cedb2010-09-19 09:31:09 +000039 asynchronously and several calls to *func* may be made concurrently. The
Brian Quinlan81c4d362010-09-18 22:35:02 +000040 returned iterator raises a :exc:`TimeoutError` if :meth:`__next__()` is
41 called and the result isn't available after *timeout* seconds from the
Benjamin Petersonc713fc72010-09-19 04:23:17 +000042 original call to :meth:`Executor.map`. *timeout* can be an int or a
Georg Brandl035cedb2010-09-19 09:31:09 +000043 float. If *timeout* is not specified or ``None``, there is no limit to
44 the wait time. If a call raises an exception, then that exception will
45 be raised when its value is retrieved from the iterator.
Brian Quinlan81c4d362010-09-18 22:35:02 +000046
47 .. method:: shutdown(wait=True)
48
49 Signal the executor that it should free any resources that it is using
Georg Brandl035cedb2010-09-19 09:31:09 +000050 when the currently pending futures are done executing. Calls to
Brian Quinlan81c4d362010-09-18 22:35:02 +000051 :meth:`Executor.submit` and :meth:`Executor.map` made after shutdown will
52 raise :exc:`RuntimeError`.
53
Benjamin Petersonc713fc72010-09-19 04:23:17 +000054 If *wait* is ``True`` then this method will not return until all the
Brian Quinlan81c4d362010-09-18 22:35:02 +000055 pending futures are done executing and the resources associated with the
Georg Brandl035cedb2010-09-19 09:31:09 +000056 executor have been freed. If *wait* is ``False`` then this method will
Benjamin Petersonc713fc72010-09-19 04:23:17 +000057 return immediately and the resources associated with the executor will be
Georg Brandl035cedb2010-09-19 09:31:09 +000058 freed when all pending futures are done executing. Regardless of the
Brian Quinlan81c4d362010-09-18 22:35:02 +000059 value of *wait*, the entire Python program will not exit until all
60 pending futures are done executing.
61
Georg Brandl035cedb2010-09-19 09:31:09 +000062 You can avoid having to call this method explicitly if you use the
63 :keyword:`with` statement, which will shutdown the :class:`Executor`
64 (waiting as if :meth:`Executor.shutdown` were called with *wait* set to
65 ``True``)::
Brian Quinlan81c4d362010-09-18 22:35:02 +000066
Georg Brandl035cedb2010-09-19 09:31:09 +000067 import shutil
68 with ThreadPoolExecutor(max_workers=4) as e:
69 e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
70 e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
71 e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
72 e.submit(shutil.copy, 'src3.txt', 'dest4.txt')
Brian Quinlan81c4d362010-09-18 22:35:02 +000073
Brian Quinlan81c4d362010-09-18 22:35:02 +000074
75ThreadPoolExecutor
Georg Brandl035cedb2010-09-19 09:31:09 +000076------------------
Brian Quinlan81c4d362010-09-18 22:35:02 +000077
Benjamin Petersonc713fc72010-09-19 04:23:17 +000078:class:`ThreadPoolExecutor` is a :class:`Executor` subclass that uses a pool of
79threads to execute calls asynchronously.
Brian Quinlan81c4d362010-09-18 22:35:02 +000080
Benjamin Petersonc713fc72010-09-19 04:23:17 +000081Deadlocks can occur when the callable associated with a :class:`Future` waits on
Georg Brandl035cedb2010-09-19 09:31:09 +000082the results of another :class:`Future`. For example::
Brian Quinlan81c4d362010-09-18 22:35:02 +000083
Georg Brandl035cedb2010-09-19 09:31:09 +000084 import time
85 def wait_on_b():
86 time.sleep(5)
87 print(b.result()) # b will never complete because it is waiting on a.
88 return 5
Brian Quinlan81c4d362010-09-18 22:35:02 +000089
Georg Brandl035cedb2010-09-19 09:31:09 +000090 def wait_on_a():
91 time.sleep(5)
92 print(a.result()) # a will never complete because it is waiting on b.
93 return 6
Brian Quinlan81c4d362010-09-18 22:35:02 +000094
95
Georg Brandl035cedb2010-09-19 09:31:09 +000096 executor = ThreadPoolExecutor(max_workers=2)
97 a = executor.submit(wait_on_b)
98 b = executor.submit(wait_on_a)
Brian Quinlan81c4d362010-09-18 22:35:02 +000099
Georg Brandl035cedb2010-09-19 09:31:09 +0000100And::
Brian Quinlan81c4d362010-09-18 22:35:02 +0000101
Georg Brandl035cedb2010-09-19 09:31:09 +0000102 def wait_on_future():
103 f = executor.submit(pow, 5, 2)
104 # This will never complete because there is only one worker thread and
105 # it is executing this function.
106 print(f.result())
Brian Quinlan81c4d362010-09-18 22:35:02 +0000107
Georg Brandl035cedb2010-09-19 09:31:09 +0000108 executor = ThreadPoolExecutor(max_workers=1)
109 executor.submit(wait_on_future)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000110
111
112.. class:: ThreadPoolExecutor(max_workers)
113
114 An :class:`Executor` subclass that uses a pool of at most *max_workers*
115 threads to execute calls asynchronously.
116
Georg Brandl035cedb2010-09-19 09:31:09 +0000117
Brian Quinlan81c4d362010-09-18 22:35:02 +0000118.. _threadpoolexecutor-example:
119
120ThreadPoolExecutor Example
Georg Brandl035cedb2010-09-19 09:31:09 +0000121~~~~~~~~~~~~~~~~~~~~~~~~~~
Brian Quinlan81c4d362010-09-18 22:35:02 +0000122::
123
Georg Brandl035cedb2010-09-19 09:31:09 +0000124 import concurrent.futures
125 import urllib.request
Brian Quinlan81c4d362010-09-18 22:35:02 +0000126
Georg Brandl035cedb2010-09-19 09:31:09 +0000127 URLS = ['http://www.foxnews.com/',
128 'http://www.cnn.com/',
129 'http://europe.wsj.com/',
130 'http://www.bbc.co.uk/',
131 'http://some-made-up-domain.com/']
Brian Quinlan81c4d362010-09-18 22:35:02 +0000132
Georg Brandl035cedb2010-09-19 09:31:09 +0000133 def load_url(url, timeout):
134 return urllib.request.urlopen(url, timeout=timeout).read()
Brian Quinlan81c4d362010-09-18 22:35:02 +0000135
Georg Brandl035cedb2010-09-19 09:31:09 +0000136 with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
137 future_to_url = dict((executor.submit(load_url, url, 60), url)
138 for url in URLS)
Brian Quinlan81c4d362010-09-18 22:35:02 +0000139
Georg Brandl035cedb2010-09-19 09:31:09 +0000140 for future in concurrent.futures.as_completed(future_to_url):
141 url = future_to_url[future]
142 if future.exception() is not None:
143 print('%r generated an exception: %s' % (url,
144 future.exception()))
145 else:
146 print('%r page is %d bytes' % (url, len(future.result())))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000147
148
149ProcessPoolExecutor
Georg Brandl035cedb2010-09-19 09:31:09 +0000150-------------------
Brian Quinlan81c4d362010-09-18 22:35:02 +0000151
152The :class:`ProcessPoolExecutor` class is an :class:`Executor` subclass that
153uses a pool of processes to execute calls asynchronously.
154:class:`ProcessPoolExecutor` uses the :mod:`multiprocessing` module, which
155allows it to side-step the :term:`Global Interpreter Lock` but also means that
156only picklable objects can be executed and returned.
157
158Calling :class:`Executor` or :class:`Future` methods from a callable submitted
159to a :class:`ProcessPoolExecutor` will result in deadlock.
160
161.. class:: ProcessPoolExecutor(max_workers=None)
162
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000163 An :class:`Executor` subclass that executes calls asynchronously using a pool
Georg Brandl035cedb2010-09-19 09:31:09 +0000164 of at most *max_workers* processes. If *max_workers* is ``None`` or not
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000165 given, it will default to the number of processors on the machine.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000166
Georg Brandl035cedb2010-09-19 09:31:09 +0000167
Brian Quinlan81c4d362010-09-18 22:35:02 +0000168.. _processpoolexecutor-example:
169
170ProcessPoolExecutor Example
Georg Brandl035cedb2010-09-19 09:31:09 +0000171~~~~~~~~~~~~~~~~~~~~~~~~~~~
Brian Quinlan81c4d362010-09-18 22:35:02 +0000172::
173
Georg Brandl035cedb2010-09-19 09:31:09 +0000174 import concurrent.futures
175 import math
Brian Quinlan81c4d362010-09-18 22:35:02 +0000176
Georg Brandl035cedb2010-09-19 09:31:09 +0000177 PRIMES = [
178 112272535095293,
179 112582705942171,
180 112272535095293,
181 115280095190773,
182 115797848077099,
183 1099726899285419]
Brian Quinlan81c4d362010-09-18 22:35:02 +0000184
Georg Brandl035cedb2010-09-19 09:31:09 +0000185 def is_prime(n):
186 if n % 2 == 0:
187 return False
Brian Quinlan81c4d362010-09-18 22:35:02 +0000188
Georg Brandl035cedb2010-09-19 09:31:09 +0000189 sqrt_n = int(math.floor(math.sqrt(n)))
190 for i in range(3, sqrt_n + 1, 2):
191 if n % i == 0:
192 return False
193 return True
Brian Quinlan81c4d362010-09-18 22:35:02 +0000194
Georg Brandl035cedb2010-09-19 09:31:09 +0000195 def main():
196 with concurrent.futures.ProcessPoolExecutor() as executor:
197 for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
198 print('%d is prime: %s' % (number, prime))
Brian Quinlan81c4d362010-09-18 22:35:02 +0000199
Georg Brandl035cedb2010-09-19 09:31:09 +0000200 if __name__ == '__main__':
201 main()
202
Brian Quinlan81c4d362010-09-18 22:35:02 +0000203
204Future Objects
Georg Brandl035cedb2010-09-19 09:31:09 +0000205--------------
Brian Quinlan81c4d362010-09-18 22:35:02 +0000206
Georg Brandl6faee4e2010-09-21 14:48:28 +0000207The :class:`Future` class encapsulates the asynchronous execution of a callable.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000208:class:`Future` instances are created by :meth:`Executor.submit`.
209
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000210.. class:: Future
Brian Quinlan81c4d362010-09-18 22:35:02 +0000211
Georg Brandl6faee4e2010-09-21 14:48:28 +0000212 Encapsulates the asynchronous execution of a callable. :class:`Future`
Brian Quinlan81c4d362010-09-18 22:35:02 +0000213 instances are created by :meth:`Executor.submit` and should not be created
214 directly except for testing.
215
216 .. method:: cancel()
217
Georg Brandl035cedb2010-09-19 09:31:09 +0000218 Attempt to cancel the call. If the call is currently being executed and
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000219 cannot be cancelled and the method will return ``False``, otherwise the
220 call will be cancelled and the method will return ``True``.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000221
222 .. method:: cancelled()
223
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000224 Return ``True`` if the call was successfully cancelled.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000225
226 .. method:: running()
227
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000228 Return ``True`` if the call is currently being executed and cannot be
Brian Quinlan81c4d362010-09-18 22:35:02 +0000229 cancelled.
230
231 .. method:: done()
232
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000233 Return ``True`` if the call was successfully cancelled or finished
234 running.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000235
236 .. method:: result(timeout=None)
237
238 Return the value returned by the call. If the call hasn't yet completed
Georg Brandl035cedb2010-09-19 09:31:09 +0000239 then this method will wait up to *timeout* seconds. If the call hasn't
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000240 completed in *timeout* seconds, then a :exc:`TimeoutError` will be
Georg Brandl035cedb2010-09-19 09:31:09 +0000241 raised. *timeout* can be an int or float. If *timeout* is not specified
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000242 or ``None``, there is no limit to the wait time.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000243
244 If the future is cancelled before completing then :exc:`CancelledError`
245 will be raised.
246
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000247 If the call raised, this method will raise the same exception.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000248
249 .. method:: exception(timeout=None)
250
Georg Brandl035cedb2010-09-19 09:31:09 +0000251 Return the exception raised by the call. If the call hasn't yet
252 completed then this method will wait up to *timeout* seconds. If the
253 call hasn't completed in *timeout* seconds, then a :exc:`TimeoutError`
254 will be raised. *timeout* can be an int or float. If *timeout* is not
255 specified or ``None``, there is no limit to the wait time.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000256
257 If the future is cancelled before completing then :exc:`CancelledError`
258 will be raised.
259
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000260 If the call completed without raising, ``None`` is returned.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000261
262 .. method:: add_done_callback(fn)
263
Georg Brandl035cedb2010-09-19 09:31:09 +0000264 Attaches the callable *fn* to the future. *fn* will be called, with the
Brian Quinlan81c4d362010-09-18 22:35:02 +0000265 future as its only argument, when the future is cancelled or finishes
266 running.
267
268 Added callables are called in the order that they were added and are
Georg Brandl035cedb2010-09-19 09:31:09 +0000269 always called in a thread belonging to the process that added them. If
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000270 the callable raises a :exc:`Exception` subclass, it will be logged and
Georg Brandl035cedb2010-09-19 09:31:09 +0000271 ignored. If the callable raises a :exc:`BaseException` subclass, the
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000272 behavior is undefined.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000273
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000274 If the future has already completed or been cancelled, *fn* will be
Brian Quinlan81c4d362010-09-18 22:35:02 +0000275 called immediately.
276
277 The following :class:`Future` methods are meant for use in unit tests and
278 :class:`Executor` implementations.
279
280 .. method:: set_running_or_notify_cancel()
281
282 This method should only be called by :class:`Executor` implementations
Georg Brandl035cedb2010-09-19 09:31:09 +0000283 before executing the work associated with the :class:`Future` and by unit
284 tests.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000285
Senthil Kumaran916bd382010-10-15 12:55:19 +0000286 If the method returns ``False`` then the :class:`Future` was cancelled,
Georg Brandl035cedb2010-09-19 09:31:09 +0000287 i.e. :meth:`Future.cancel` was called and returned `True`. Any threads
288 waiting on the :class:`Future` completing (i.e. through
289 :func:`as_completed` or :func:`wait`) will be woken up.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000290
Senthil Kumaran916bd382010-10-15 12:55:19 +0000291 If the method returns ``True`` then the :class:`Future` was not cancelled
Georg Brandl035cedb2010-09-19 09:31:09 +0000292 and has been put in the running state, i.e. calls to
Brian Quinlan81c4d362010-09-18 22:35:02 +0000293 :meth:`Future.running` will return `True`.
294
295 This method can only be called once and cannot be called after
296 :meth:`Future.set_result` or :meth:`Future.set_exception` have been
297 called.
298
299 .. method:: set_result(result)
300
301 Sets the result of the work associated with the :class:`Future` to
302 *result*.
303
304 This method should only be used by :class:`Executor` implementations and
305 unit tests.
306
307 .. method:: set_exception(exception)
308
309 Sets the result of the work associated with the :class:`Future` to the
310 :class:`Exception` *exception*.
311
312 This method should only be used by :class:`Executor` implementations and
313 unit tests.
314
315
316Module Functions
Georg Brandl035cedb2010-09-19 09:31:09 +0000317----------------
Brian Quinlan81c4d362010-09-18 22:35:02 +0000318
319.. function:: wait(fs, timeout=None, return_when=ALL_COMPLETED)
320
321 Wait for the :class:`Future` instances (possibly created by different
Georg Brandl035cedb2010-09-19 09:31:09 +0000322 :class:`Executor` instances) given by *fs* to complete. Returns a named
323 2-tuple of sets. The first set, named ``done``, contains the futures that
324 completed (finished or were cancelled) before the wait completed. The second
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000325 set, named ``not_done``, contains uncompleted futures.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000326
327 *timeout* can be used to control the maximum number of seconds to wait before
Georg Brandl035cedb2010-09-19 09:31:09 +0000328 returning. *timeout* can be an int or float. If *timeout* is not specified
329 or ``None``, there is no limit to the wait time.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000330
Georg Brandl035cedb2010-09-19 09:31:09 +0000331 *return_when* indicates when this function should return. It must be one of
Brian Quinlan81c4d362010-09-18 22:35:02 +0000332 the following constants:
333
Georg Brandl035cedb2010-09-19 09:31:09 +0000334 +-----------------------------+----------------------------------------+
335 | Constant | Description |
336 +=============================+========================================+
337 | :const:`FIRST_COMPLETED` | The function will return when any |
338 | | future finishes or is cancelled. |
339 +-----------------------------+----------------------------------------+
340 | :const:`FIRST_EXCEPTION` | The function will return when any |
341 | | future finishes by raising an |
342 | | exception. If no future raises an |
343 | | exception then it is equivalent to |
344 | | :const:`ALL_COMPLETED`. |
345 +-----------------------------+----------------------------------------+
346 | :const:`ALL_COMPLETED` | The function will return when all |
347 | | futures finish or are cancelled. |
348 +-----------------------------+----------------------------------------+
Brian Quinlan81c4d362010-09-18 22:35:02 +0000349
350.. function:: as_completed(fs, timeout=None)
351
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000352 Returns an iterator over the :class:`Future` instances (possibly created by
353 different :class:`Executor` instances) given by *fs* that yields futures as
Georg Brandl035cedb2010-09-19 09:31:09 +0000354 they complete (finished or were cancelled). Any futures that completed
355 before :func:`as_completed` is called will be yielded first. The returned
356 iterator raises a :exc:`TimeoutError` if :meth:`__next__` is called and the
357 result isn't available after *timeout* seconds from the original call to
358 :func:`as_completed`. *timeout* can be an int or float. If *timeout* is not
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000359 specified or ``None``, there is no limit to the wait time.
Georg Brandl035cedb2010-09-19 09:31:09 +0000360
361
362.. seealso::
363
364 :pep:`3148` -- futures - execute computations asynchronously
365 The proposal which described this feature for inclusion in the Python
366 standard library.