Debian Codegraph @

Doc/library/concurrent.futures.rst

raw
1 :mod:`!concurrent.futures` --- Launching parallel tasks
2 =======================================================
3
4 .. module:: concurrent.futures
5 :synopsis: Execute computations concurrently using threads or processes.
6
7 .. versionadded:: 3.2
8
9 **Source code:** :source:`Lib/concurrent/futures/thread.py`
10 and :source:`Lib/concurrent/futures/process.py`
11
12 --------------
13
14 The :mod:`concurrent.futures` module provides a high-level interface for
15 asynchronously executing callables.
16
17 The asynchronous execution can be performed with threads, using
18 :class:`ThreadPoolExecutor`, or separate processes, using
19 :class:`ProcessPoolExecutor`. Both implement the same interface, which is
20 defined by the abstract :class:`Executor` class.
21
22 :class:`concurrent.futures.Future` must not be confused with
23 :class:`asyncio.Future`, which is designed for use with :mod:`asyncio`
24 tasks and coroutines. See the :doc:`asyncio's Future <asyncio-future>`
25 documentation for a detailed comparison of the two.
26
27 .. include:: ../includes/wasm-notavail.rst
28
29 Executor Objects
30 ----------------
31
32 .. class:: Executor
33
34 An abstract class that provides methods to execute calls asynchronously. It
35 should not be used directly, but through its concrete subclasses.
36
37 .. method:: submit(fn, /, *args, **kwargs)
38
39 Schedules the callable, *fn*, to be executed as ``fn(*args, **kwargs)``
40 and returns a :class:`Future` object representing the execution of the
41 callable. ::
42
43 with ThreadPoolExecutor(max_workers=1) as executor:
44 future = executor.submit(pow, 323, 1235)
45 print(future.result())
46
47 .. method:: map(fn, *iterables, timeout=None, chunksize=1)
48
49 Similar to :func:`map(fn, *iterables) <map>` except:
50
51 * the *iterables* are collected immediately rather than lazily;
52
53 * *fn* is executed asynchronously and several calls to
54 *fn* may be made concurrently.
55
56 The returned iterator raises a :exc:`TimeoutError`
57 if :meth:`~iterator.__next__` is called and the result isn't available
58 after *timeout* seconds from the original call to :meth:`Executor.map`.
59 *timeout* can be an int or a float. If *timeout* is not specified or
60 ``None``, there is no limit to the wait time.
61
62 If a *fn* call raises an exception, then that exception will be
63 raised when its value is retrieved from the iterator.
64
65 When using :class:`ProcessPoolExecutor`, this method chops *iterables*
66 into a number of chunks which it submits to the pool as separate
67 tasks. The (approximate) size of these chunks can be specified by
68 setting *chunksize* to a positive integer. For very long iterables,
69 using a large value for *chunksize* can significantly improve
70 performance compared to the default size of 1. With
71 :class:`ThreadPoolExecutor`, *chunksize* has no effect.
72
73 .. versionchanged:: 3.5
74 Added the *chunksize* argument.
75
76 .. method:: shutdown(wait=True, *, cancel_futures=False)
77
78 Signal the executor that it should free any resources that it is using
79 when the currently pending futures are done executing. Calls to
80 :meth:`Executor.submit` and :meth:`Executor.map` made after shutdown will
81 raise :exc:`RuntimeError`.
82
83 If *wait* is ``True`` then this method will not return until all the
84 pending futures are done executing and the resources associated with the
85 executor have been freed. If *wait* is ``False`` then this method will
86 return immediately and the resources associated with the executor will be
87 freed when all pending futures are done executing. Regardless of the
88 value of *wait*, the entire Python program will not exit until all
89 pending futures are done executing.
90
91 If *cancel_futures* is ``True``, this method will cancel all pending
92 futures that the executor has not started running. Any futures that
93 are completed or running won't be cancelled, regardless of the value
94 of *cancel_futures*.
95
96 If both *cancel_futures* and *wait* are ``True``, all futures that the
97 executor has started running will be completed prior to this method
98 returning. The remaining futures are cancelled.
99
100 You can avoid having to call this method explicitly if you use the executor
101 as a :term:`context manager` via the :keyword:`with` statement, which
102 will shutdown the :class:`Executor` (waiting as if :meth:`Executor.shutdown`
103 were called with *wait* set to ``True``)::
104
105 import shutil
106 with ThreadPoolExecutor(max_workers=4) as e:
107 e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
108 e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
109 e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
110 e.submit(shutil.copy, 'src4.txt', 'dest4.txt')
111
112 .. versionchanged:: 3.9
113 Added *cancel_futures*.
114
115
116 ThreadPoolExecutor
117 ------------------
118
119 :class:`ThreadPoolExecutor` is an :class:`Executor` subclass that uses a pool of
120 threads to execute calls asynchronously.
121
122 Deadlocks can occur when the callable associated with a :class:`Future` waits on
123 the results of another :class:`Future`. For example::
124
125 import time
126 def wait_on_b():
127 time.sleep(5)
128 print(b.result()) # b will never complete because it is waiting on a.
129 return 5
130
131 def wait_on_a():
132 time.sleep(5)
133 print(a.result()) # a will never complete because it is waiting on b.
134 return 6
135
136
137 executor = ThreadPoolExecutor(max_workers=2)
138 a = executor.submit(wait_on_b)
139 b = executor.submit(wait_on_a)
140
141 And::
142
143 def wait_on_future():
144 f = executor.submit(pow, 5, 2)
145 # This will never complete because there is only one worker thread and
146 # it is executing this function.
147 print(f.result())
148
149 executor = ThreadPoolExecutor(max_workers=1)
150 executor.submit(wait_on_future)
151
152
153 .. class:: ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
154
155 An :class:`Executor` subclass that uses a pool of at most *max_workers*
156 threads to execute calls asynchronously.
157
158 All threads enqueued to ``ThreadPoolExecutor`` will be joined before the
159 interpreter can exit. Note that the exit handler which does this is
160 executed *before* any exit handlers added using ``atexit``. This means
161 exceptions in the main thread must be caught and handled in order to
162 signal threads to exit gracefully. For this reason, it is recommended
163 that ``ThreadPoolExecutor`` not be used for long-running tasks.
164
165 *initializer* is an optional callable that is called at the start of
166 each worker thread; *initargs* is a tuple of arguments passed to the
167 initializer. Should *initializer* raise an exception, all currently
168 pending jobs will raise a :exc:`~concurrent.futures.thread.BrokenThreadPool`,
169 as well as any attempt to submit more jobs to the pool.
170
171 .. versionchanged:: 3.5
172 If *max_workers* is ``None`` or
173 not given, it will default to the number of processors on the machine,
174 multiplied by ``5``, assuming that :class:`ThreadPoolExecutor` is often
175 used to overlap I/O instead of CPU work and the number of workers
176 should be higher than the number of workers
177 for :class:`ProcessPoolExecutor`.
178
179 .. versionchanged:: 3.6
180 Added the *thread_name_prefix* parameter to allow users to
181 control the :class:`threading.Thread` names for worker threads created by
182 the pool for easier debugging.
183
184 .. versionchanged:: 3.7
185 Added the *initializer* and *initargs* arguments.
186
187 .. versionchanged:: 3.8
188 Default value of *max_workers* is changed to ``min(32, os.cpu_count() + 4)``.
189 This default value preserves at least 5 workers for I/O bound tasks.
190 It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL.
191 And it avoids using very large resources implicitly on many-core machines.
192
193 ThreadPoolExecutor now reuses idle worker threads before starting
194 *max_workers* worker threads too.
195
196 .. versionchanged:: 3.13
197 Default value of *max_workers* is changed to
198 ``min(32, (os.process_cpu_count() or 1) + 4)``.
199
200
201 .. _threadpoolexecutor-example:
202
203 ThreadPoolExecutor Example
204 ~~~~~~~~~~~~~~~~~~~~~~~~~~
205 ::
206
207 import concurrent.futures
208 import urllib.request
209
210 URLS = ['http://www.foxnews.com/',
211 'http://www.cnn.com/',
212 'http://europe.wsj.com/',
213 'http://www.bbc.co.uk/',
214 'http://nonexistent-subdomain.python.org/']
215
216 # Retrieve a single page and report the URL and contents
217 def load_url(url, timeout):
218 with urllib.request.urlopen(url, timeout=timeout) as conn:
219 return conn.read()
220
221 # We can use a with statement to ensure threads are cleaned up promptly
222 with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
223 # Start the load operations and mark each future with its URL
224 future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
225 for future in concurrent.futures.as_completed(future_to_url):
226 url = future_to_url[future]
227 try:
228 data = future.result()
229 except Exception as exc:
230 print('%r generated an exception: %s' % (url, exc))
231 else:
232 print('%r page is %d bytes' % (url, len(data)))
233
234
235 ProcessPoolExecutor
236 -------------------
237
238 The :class:`ProcessPoolExecutor` class is an :class:`Executor` subclass that
239 uses a pool of processes to execute calls asynchronously.
240 :class:`ProcessPoolExecutor` uses the :mod:`multiprocessing` module, which
241 allows it to side-step the :term:`Global Interpreter Lock
242 <global interpreter lock>` but also means that
243 only picklable objects can be executed and returned.
244
245 The ``__main__`` module must be importable by worker subprocesses. This means
246 that :class:`ProcessPoolExecutor` will not work in the interactive interpreter.
247
248 Calling :class:`Executor` or :class:`Future` methods from a callable submitted
249 to a :class:`ProcessPoolExecutor` will result in deadlock.
250
251 Note that the restrictions on functions and arguments needing to picklable as
252 per :class:`multiprocessing.Process` apply when using :meth:`~Executor.submit`
253 and :meth:`~Executor.map` on a :class:`ProcessPoolExecutor`. A function defined
254 in a REPL or a lambda should not be expected to work.
255
256 .. class:: ProcessPoolExecutor(max_workers=None, mp_context=None, initializer=None, initargs=(), max_tasks_per_child=None)
257
258 An :class:`Executor` subclass that executes calls asynchronously using a pool
259 of at most *max_workers* processes. If *max_workers* is ``None`` or not
260 given, it will default to :func:`os.process_cpu_count`.
261 If *max_workers* is less than or equal to ``0``, then a :exc:`ValueError`
262 will be raised.
263 On Windows, *max_workers* must be less than or equal to ``61``. If it is not
264 then :exc:`ValueError` will be raised. If *max_workers* is ``None``, then
265 the default chosen will be at most ``61``, even if more processors are
266 available.
267 *mp_context* can be a :mod:`multiprocessing` context or ``None``. It will be
268 used to launch the workers. If *mp_context* is ``None`` or not given, the
269 default :mod:`multiprocessing` context is used.
270 See :ref:`multiprocessing-start-methods`.
271
272 *initializer* is an optional callable that is called at the start of
273 each worker process; *initargs* is a tuple of arguments passed to the
274 initializer. Should *initializer* raise an exception, all currently
275 pending jobs will raise a :exc:`~concurrent.futures.process.BrokenProcessPool`,
276 as well as any attempt to submit more jobs to the pool.
277
278 *max_tasks_per_child* is an optional argument that specifies the maximum
279 number of tasks a single process can execute before it will exit and be
280 replaced with a fresh worker process. By default *max_tasks_per_child* is
281 ``None`` which means worker processes will live as long as the pool. When
282 a max is specified, the "spawn" multiprocessing start method will be used by
283 default in absence of a *mp_context* parameter. This feature is incompatible
284 with the "fork" start method.
285
286 .. note::
287 Bugs have been reported when using the *max_tasks_per_child* feature that
288 can result in the :class:`ProcessPoolExecutor` hanging in some
289 circumstances. Follow its eventual resolution in :gh:`115634`.
290
291 .. versionchanged:: 3.3
292 When one of the worker processes terminates abruptly, a
293 :exc:`~concurrent.futures.process.BrokenProcessPool` error is now raised.
294 Previously, behaviour
295 was undefined but operations on the executor or its futures would often
296 freeze or deadlock.
297
298 .. versionchanged:: 3.7
299 The *mp_context* argument was added to allow users to control the
300 start_method for worker processes created by the pool.
301
302 Added the *initializer* and *initargs* arguments.
303
304 .. note::
305 The default :mod:`multiprocessing` start method
306 (see :ref:`multiprocessing-start-methods`) will change away from
307 *fork* in Python 3.14. Code that requires *fork* be used for their
308 :class:`ProcessPoolExecutor` should explicitly specify that by
309 passing a ``mp_context=multiprocessing.get_context("fork")``
310 parameter.
311
312 .. versionchanged:: 3.11
313 The *max_tasks_per_child* argument was added to allow users to
314 control the lifetime of workers in the pool.
315
316 .. versionchanged:: 3.12
317 On POSIX systems, if your application has multiple threads and the
318 :mod:`multiprocessing` context uses the ``"fork"`` start method:
319 The :func:`os.fork` function called internally to spawn workers may raise a
320 :exc:`DeprecationWarning`. Pass a *mp_context* configured to use a
321 different start method. See the :func:`os.fork` documentation for
322 further explanation.
323
324 .. versionchanged:: 3.13
325 *max_workers* uses :func:`os.process_cpu_count` by default, instead of
326 :func:`os.cpu_count`.
327
328 .. _processpoolexecutor-example:
329
330 ProcessPoolExecutor Example
331 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
332 ::
333
334 import concurrent.futures
335 import math
336
337 PRIMES = [
338 112272535095293,
339 112582705942171,
340 112272535095293,
341 115280095190773,
342 115797848077099,
343 1099726899285419]
344
345 def is_prime(n):
346 if n < 2:
347 return False
348 if n == 2:
349 return True
350 if n % 2 == 0:
351 return False
352
353 sqrt_n = int(math.floor(math.sqrt(n)))
354 for i in range(3, sqrt_n + 1, 2):
355 if n % i == 0:
356 return False
357 return True
358
359 def main():
360 with concurrent.futures.ProcessPoolExecutor() as executor:
361 for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
362 print('%d is prime: %s' % (number, prime))
363
364 if __name__ == '__main__':
365 main()
366
367
368 Future Objects
369 --------------
370
371 The :class:`Future` class encapsulates the asynchronous execution of a callable.
372 :class:`Future` instances are created by :meth:`Executor.submit`.
373
374 .. class:: Future
375
376 Encapsulates the asynchronous execution of a callable. :class:`Future`
377 instances are created by :meth:`Executor.submit` and should not be created
378 directly except for testing.
379
380 .. method:: cancel()
381
382 Attempt to cancel the call. If the call is currently being executed or
383 finished running and cannot be cancelled then the method will return
384 ``False``, otherwise the call will be cancelled and the method will
385 return ``True``.
386
387 .. method:: cancelled()
388
389 Return ``True`` if the call was successfully cancelled.
390
391 .. method:: running()
392
393 Return ``True`` if the call is currently being executed and cannot be
394 cancelled.
395
396 .. method:: done()
397
398 Return ``True`` if the call was successfully cancelled or finished
399 running.
400
401 .. method:: result(timeout=None)
402
403 Return the value returned by the call. If the call hasn't yet completed
404 then this method will wait up to *timeout* seconds. If the call hasn't
405 completed in *timeout* seconds, then a
406 :exc:`TimeoutError` will be raised. *timeout* can be
407 an int or float. If *timeout* is not specified or ``None``, there is no
408 limit to the wait time.
409
410 If the future is cancelled before completing then :exc:`.CancelledError`
411 will be raised.
412
413 If the call raised an exception, this method will raise the same exception.
414
415 .. method:: exception(timeout=None)
416
417 Return the exception raised by the call. If the call hasn't yet
418 completed then this method will wait up to *timeout* seconds. If the
419 call hasn't completed in *timeout* seconds, then a
420 :exc:`TimeoutError` will be raised. *timeout* can be
421 an int or float. If *timeout* is not specified or ``None``, there is no
422 limit to the wait time.
423
424 If the future is cancelled before completing then :exc:`.CancelledError`
425 will be raised.
426
427 If the call completed without raising, ``None`` is returned.
428
429 .. method:: add_done_callback(fn)
430
431 Attaches the callable *fn* to the future. *fn* will be called, with the
432 future as its only argument, when the future is cancelled or finishes
433 running.
434
435 Added callables are called in the order that they were added and are
436 always called in a thread belonging to the process that added them. If
437 the callable raises an :exc:`Exception` subclass, it will be logged and
438 ignored. If the callable raises a :exc:`BaseException` subclass, the
439 behavior is undefined.
440
441 If the future has already completed or been cancelled, *fn* will be
442 called immediately.
443
444 The following :class:`Future` methods are meant for use in unit tests and
445 :class:`Executor` implementations.
446
447 .. method:: set_running_or_notify_cancel()
448
449 This method should only be called by :class:`Executor` implementations
450 before executing the work associated with the :class:`Future` and by unit
451 tests.
452
453 If the method returns ``False`` then the :class:`Future` was cancelled,
454 i.e. :meth:`Future.cancel` was called and returned ``True``. Any threads
455 waiting on the :class:`Future` completing (i.e. through
456 :func:`as_completed` or :func:`wait`) will be woken up.
457
458 If the method returns ``True`` then the :class:`Future` was not cancelled
459 and has been put in the running state, i.e. calls to
460 :meth:`Future.running` will return ``True``.
461
462 This method can only be called once and cannot be called after
463 :meth:`Future.set_result` or :meth:`Future.set_exception` have been
464 called.
465
466 .. method:: set_result(result)
467
468 Sets the result of the work associated with the :class:`Future` to
469 *result*.
470
471 This method should only be used by :class:`Executor` implementations and
472 unit tests.
473
474 .. versionchanged:: 3.8
475 This method raises
476 :exc:`concurrent.futures.InvalidStateError` if the :class:`Future` is
477 already done.
478
479 .. method:: set_exception(exception)
480
481 Sets the result of the work associated with the :class:`Future` to the
482 :class:`Exception` *exception*.
483
484 This method should only be used by :class:`Executor` implementations and
485 unit tests.
486
487 .. versionchanged:: 3.8
488 This method raises
489 :exc:`concurrent.futures.InvalidStateError` if the :class:`Future` is
490 already done.
491
492 Module Functions
493 ----------------
494
495 .. function:: wait(fs, timeout=None, return_when=ALL_COMPLETED)
496
497 Wait for the :class:`Future` instances (possibly created by different
498 :class:`Executor` instances) given by *fs* to complete. Duplicate futures
499 given to *fs* are removed and will be returned only once. Returns a named
500 2-tuple of sets. The first set, named ``done``, contains the futures that
501 completed (finished or cancelled futures) before the wait completed. The
502 second set, named ``not_done``, contains the futures that did not complete
503 (pending or running futures).
504
505 *timeout* can be used to control the maximum number of seconds to wait before
506 returning. *timeout* can be an int or float. If *timeout* is not specified
507 or ``None``, there is no limit to the wait time.
508
509 *return_when* indicates when this function should return. It must be one of
510 the following constants:
511
512 .. list-table::
513 :header-rows: 1
514
515 * - Constant
516 - Description
517
518 * - .. data:: FIRST_COMPLETED
519 - The function will return when any future finishes or is cancelled.
520
521 * - .. data:: FIRST_EXCEPTION
522 - The function will return when any future finishes by raising an
523 exception. If no future raises an exception
524 then it is equivalent to :const:`ALL_COMPLETED`.
525
526 * - .. data:: ALL_COMPLETED
527 - The function will return when all futures finish or are cancelled.
528
529 .. function:: as_completed(fs, timeout=None)
530
531 Returns an iterator over the :class:`Future` instances (possibly created by
532 different :class:`Executor` instances) given by *fs* that yields futures as
533 they complete (finished or cancelled futures). Any futures given by *fs* that
534 are duplicated will be returned once. Any futures that completed before
535 :func:`as_completed` is called will be yielded first. The returned iterator
536 raises a :exc:`TimeoutError` if :meth:`~iterator.__next__`
537 is called and the result isn't available after *timeout* seconds from the
538 original call to :func:`as_completed`. *timeout* can be an int or float. If
539 *timeout* is not specified or ``None``, there is no limit to the wait time.
540
541
542 .. seealso::
543
544 :pep:`3148` -- futures - execute computations asynchronously
545 The proposal which described this feature for inclusion in the Python
546 standard library.
547
548
549 Exception classes
550 -----------------
551
552 .. currentmodule:: concurrent.futures
553
554 .. exception:: CancelledError
555
556 Raised when a future is cancelled.
557
558 .. exception:: TimeoutError
559
560 A deprecated alias of :exc:`TimeoutError`,
561 raised when a future operation exceeds the given timeout.
562
563 .. versionchanged:: 3.11
564
565 This class was made an alias of :exc:`TimeoutError`.
566
567
568 .. exception:: BrokenExecutor
569
570 Derived from :exc:`RuntimeError`, this exception class is raised
571 when an executor is broken for some reason, and cannot be used
572 to submit or execute new tasks.
573
574 .. versionadded:: 3.7
575
576 .. exception:: InvalidStateError
577
578 Raised when an operation is performed on a future that is not allowed
579 in the current state.
580
581 .. versionadded:: 3.8
582
583 .. currentmodule:: concurrent.futures.thread
584
585 .. exception:: BrokenThreadPool
586
587 Derived from :exc:`~concurrent.futures.BrokenExecutor`, this exception
588 class is raised when one of the workers
589 of a :class:`~concurrent.futures.ThreadPoolExecutor`
590 has failed initializing.
591
592 .. versionadded:: 3.7
593
594 .. currentmodule:: concurrent.futures.process
595
596 .. exception:: BrokenProcessPool
597
598 Derived from :exc:`~concurrent.futures.BrokenExecutor` (formerly
599 :exc:`RuntimeError`), this exception class is raised when one of the
600 workers of a :class:`~concurrent.futures.ProcessPoolExecutor`
601 has terminated in a non-clean
602 fashion (for example, if it was killed from the outside).
603
604 .. versionadded:: 3.3