blob: 11a529663c61c4291250879bf15cff7b43b05813 [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
7The :mod:`concurrent.futures` module provides a high-level interface for
8asynchronously executing callables.
9
Benjamin Petersonc713fc72010-09-19 04:23:17 +000010The asynchronous execution can be be performed with threads, using
11:class:`ThreadPoolExecutor`, or seperate processes, using
Brian Quinlan81c4d362010-09-18 22:35:02 +000012:class:`ProcessPoolExecutor`. Both implement the same interface, which is
13defined by the abstract :class:`Executor` class.
14
15Executor Objects
16^^^^^^^^^^^^^^^^
17
Benjamin Petersonc713fc72010-09-19 04:23:17 +000018.. class:: Executor
Brian Quinlan81c4d362010-09-18 22:35:02 +000019
20 An abstract class that provides methods to execute calls asynchronously. It
Benjamin Petersonc713fc72010-09-19 04:23:17 +000021 should not be used directly, but through its concrete subclasses.
Brian Quinlan81c4d362010-09-18 22:35:02 +000022
23 .. method:: submit(fn, *args, **kwargs)
24
Benjamin Petersonc713fc72010-09-19 04:23:17 +000025 Schedules the callable, *fn*, to be executed as ``fn(*args **kwargs)``
26 and returns a :class:`Future` object representing the execution of the
27 callable.
Brian Quinlan81c4d362010-09-18 22:35:02 +000028
29 ::
30
31 with ThreadPoolExecutor(max_workers=1) as executor:
32 future = executor.submit(pow, 323, 1235)
33 print(future.result())
34
35 .. method:: map(func, *iterables, timeout=None)
36
Benjamin Petersonc713fc72010-09-19 04:23:17 +000037 Equivalent to ``map(func, *iterables)`` except *func* is executed
Brian Quinlan81c4d362010-09-18 22:35:02 +000038 asynchronously and several calls to *func* may be made concurrently. The
39 returned iterator raises a :exc:`TimeoutError` if :meth:`__next__()` is
40 called and the result isn't available after *timeout* seconds from the
Benjamin Petersonc713fc72010-09-19 04:23:17 +000041 original call to :meth:`Executor.map`. *timeout* can be an int or a
42 float. If *timeout* is not specified or ``None``, there is no limit to
43 the wait time. If a call raises an exception, then that exception will be
44 raised when its value is retrieved from the iterator.
Brian Quinlan81c4d362010-09-18 22:35:02 +000045
46 .. method:: shutdown(wait=True)
47
48 Signal the executor that it should free any resources that it is using
49 when the currently pending futures are done executing. Calls to
50 :meth:`Executor.submit` and :meth:`Executor.map` made after shutdown will
51 raise :exc:`RuntimeError`.
52
Benjamin Petersonc713fc72010-09-19 04:23:17 +000053 If *wait* is ``True`` then this method will not return until all the
Brian Quinlan81c4d362010-09-18 22:35:02 +000054 pending futures are done executing and the resources associated with the
Benjamin Petersonc713fc72010-09-19 04:23:17 +000055 executor have been freed. If *wait* is ``False`` then this method will
56 return immediately and the resources associated with the executor will be
57 freed when all pending futures are done executing. Regardless of the
Brian Quinlan81c4d362010-09-18 22:35:02 +000058 value of *wait*, the entire Python program will not exit until all
59 pending futures are done executing.
60
61 You can avoid having to call this method explicitly if you use the `with`
62 statement, which will shutdown the `Executor` (waiting as if
63 `Executor.shutdown` were called with *wait* set to `True`):
64
65 ::
66
67 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')
73
74ThreadPoolExecutor
75^^^^^^^^^^^^^^^^^^
76
Benjamin Petersonc713fc72010-09-19 04:23:17 +000077:class:`ThreadPoolExecutor` is a :class:`Executor` subclass that uses a pool of
78threads to execute calls asynchronously.
Brian Quinlan81c4d362010-09-18 22:35:02 +000079
Benjamin Petersonc713fc72010-09-19 04:23:17 +000080Deadlocks can occur when the callable associated with a :class:`Future` waits on
Brian Quinlan81c4d362010-09-18 22:35:02 +000081the results of another :class:`Future`. For example:
82
83::
84
85 import time
86 def wait_on_b():
87 time.sleep(5)
88 print(b.result()) # b will never complete because it is waiting on a.
89 return 5
90
91 def wait_on_a():
92 time.sleep(5)
93 print(a.result()) # a will never complete because it is waiting on b.
94 return 6
95
96
97 executor = ThreadPoolExecutor(max_workers=2)
98 a = executor.submit(wait_on_b)
99 b = executor.submit(wait_on_a)
100
101And:
102
103::
104
105 def wait_on_future():
106 f = executor.submit(pow, 5, 2)
107 # This will never complete because there is only one worker thread and
108 # it is executing this function.
109 print(f.result())
110
111 executor = ThreadPoolExecutor(max_workers=1)
112 executor.submit(wait_on_future)
113
114
115.. class:: ThreadPoolExecutor(max_workers)
116
117 An :class:`Executor` subclass that uses a pool of at most *max_workers*
118 threads to execute calls asynchronously.
119
Brian Quinlan81c4d362010-09-18 22:35:02 +0000120.. _threadpoolexecutor-example:
121
122ThreadPoolExecutor Example
123^^^^^^^^^^^^^^^^^^^^^^^^^^
124::
125
126 import concurrent.futures
127 import urllib.request
128
129 URLS = ['http://www.foxnews.com/',
130 'http://www.cnn.com/',
131 'http://europe.wsj.com/',
132 'http://www.bbc.co.uk/',
133 'http://some-made-up-domain.com/']
134
135 def load_url(url, timeout):
136 return urllib.request.urlopen(url, timeout=timeout).read()
137
138 with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
139 future_to_url = dict((executor.submit(load_url, url, 60), url)
140 for url in URLS)
141
142 for future in concurrent.futures.as_completed(future_to_url):
143 url = future_to_url[future]
144 if future.exception() is not None:
145 print('%r generated an exception: %s' % (url,
146 future.exception()))
147 else:
148 print('%r page is %d bytes' % (url, len(future.result())))
149
150
151ProcessPoolExecutor
152^^^^^^^^^^^^^^^^^^^
153
154The :class:`ProcessPoolExecutor` class is an :class:`Executor` subclass that
155uses a pool of processes to execute calls asynchronously.
156:class:`ProcessPoolExecutor` uses the :mod:`multiprocessing` module, which
157allows it to side-step the :term:`Global Interpreter Lock` but also means that
158only picklable objects can be executed and returned.
159
160Calling :class:`Executor` or :class:`Future` methods from a callable submitted
161to a :class:`ProcessPoolExecutor` will result in deadlock.
162
163.. class:: ProcessPoolExecutor(max_workers=None)
164
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000165 An :class:`Executor` subclass that executes calls asynchronously using a pool
166 of at most *max_workers* processes. If *max_workers* is ``None`` or not
167 given, it will default to the number of processors on the machine.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000168
169.. _processpoolexecutor-example:
170
171ProcessPoolExecutor Example
172^^^^^^^^^^^^^^^^^^^^^^^^^^^
173::
174
175 import concurrent.futures
176 import math
177
178 PRIMES = [
179 112272535095293,
180 112582705942171,
181 112272535095293,
182 115280095190773,
183 115797848077099,
184 1099726899285419]
185
186 def is_prime(n):
187 if n % 2 == 0:
188 return False
189
190 sqrt_n = int(math.floor(math.sqrt(n)))
191 for i in range(3, sqrt_n + 1, 2):
192 if n % i == 0:
193 return False
194 return True
195
196 def main():
197 with concurrent.futures.ProcessPoolExecutor() as executor:
198 for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
199 print('%d is prime: %s' % (number, prime))
200
201 if __name__ == '__main__':
202 main()
203
204Future Objects
205^^^^^^^^^^^^^^
206
207The :class:`Future` class encapulates the asynchronous execution of a callable.
208: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
212 Encapulates the asynchronous execution of a callable. :class:`Future`
213 instances are created by :meth:`Executor.submit` and should not be created
214 directly except for testing.
215
216 .. method:: cancel()
217
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000218 Attempt to cancel the call. If the call is currently being executed and
219 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
239 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
241 raised. *timeout* can be an int or float. If *timeout* is not specified
242 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
251 Return the exception raised by the call. If the call hasn't yet completed
252 then this method will wait up to *timeout* seconds. If the call hasn't
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000253 completed in *timeout* seconds, then a :exc:`TimeoutError` will be
254 raised. *timeout* can be an int or float. If *timeout* is not specified
255 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
264 Attaches the callable *fn* to the future. *fn* will be called, with the
265 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
269 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
271 ignored. If the callable raises a :exc:`BaseException` subclass, the
272 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
283 before executing the work associated with the :class:`Future` and by
284 unit tests.
285
286 If the method returns `False` then the :class:`Future` was cancelled i.e.
287 :meth:`Future.cancel` was called and returned `True`. Any threads waiting
288 on the :class:`Future` completing (i.e. through :func:`as_completed` or
289 :func:`wait`) will be woken up.
290
291 If the method returns `True` then the :class:`Future` was not cancelled
292 and has been put in the running state i.e. calls to
293 :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
317^^^^^^^^^^^^^^^^
318
319.. function:: wait(fs, timeout=None, return_when=ALL_COMPLETED)
320
321 Wait for the :class:`Future` instances (possibly created by different
Benjamin Petersonc713fc72010-09-19 04:23:17 +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
Brian Quinlan81c4d362010-09-18 22:35:02 +0000324 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
328 returning. *timeout* can be an int or float. If *timeout* is not specified or
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000329 ``None``, there is no limit to the wait time.
Brian Quinlan81c4d362010-09-18 22:35:02 +0000330
331 *return_when* indicates when this function should return. It must be one of
332 the following constants:
333
334 +-----------------------------+----------------------------------------+
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 |
Benjamin Petersonc713fc72010-09-19 04:23:17 +0000344 | | :const:`ALL_COMPLETED`. |
Brian Quinlan81c4d362010-09-18 22:35:02 +0000345 +-----------------------------+----------------------------------------+
346 | :const:`ALL_COMPLETED` | The function will return when all |
347 | | futures finish or are cancelled. |
348 +-----------------------------+----------------------------------------+
349
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
354 they complete (finished or were cancelled). Any futures that completed before
355 :func:`as_completed` is called will be yielded first. The returned iterator
356 raises a :exc:`TimeoutError` if :meth:`__next__` is called and the result
357 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
359 specified or ``None``, there is no limit to the wait time.