index.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. :mod:`concurrent.futures` --- Asynchronous computation
  2. ======================================================
  3. .. module:: concurrent.futures
  4. :synopsis: Execute computations asynchronously using threads or processes.
  5. The :mod:`concurrent.futures` module provides a high-level interface for
  6. asynchronously executing callables.
  7. The asynchronous execution can be be performed by threads using
  8. :class:`ThreadPoolExecutor` or seperate processes using
  9. :class:`ProcessPoolExecutor`. Both implement the same interface, which is
  10. defined by the abstract :class:`Executor` class.
  11. Executor Objects
  12. ----------------
  13. :class:`Executor` is an abstract class that provides methods to execute calls
  14. asynchronously. It should not be used directly, but through its two
  15. subclasses: :class:`ThreadPoolExecutor` and :class:`ProcessPoolExecutor`.
  16. .. method:: Executor.submit(fn, *args, **kwargs)
  17. Schedules the callable to be executed as *fn*(*\*args*, *\*\*kwargs*) and
  18. returns a :class:`Future` representing the execution of the callable.
  19. ::
  20. with ThreadPoolExecutor(max_workers=1) as executor:
  21. future = executor.submit(pow, 323, 1235)
  22. print(future.result())
  23. .. method:: Executor.map(func, *iterables, timeout=None)
  24. Equivalent to map(*func*, *\*iterables*) but func is executed asynchronously
  25. and several calls to *func* may be made concurrently. The returned iterator
  26. raises a :exc:`TimeoutError` if :meth:`__next__()` is called and the result
  27. isn't available after *timeout* seconds from the original call to
  28. :meth:`map()`. *timeout* can be an int or float. If *timeout* is not
  29. specified or ``None`` then there is no limit to the wait time. If a call
  30. raises an exception then that exception will be raised when its value is
  31. retrieved from the iterator.
  32. .. method:: Executor.shutdown(wait=True)
  33. Signal the executor that it should free any resources that it is using when
  34. the currently pending futures are done executing. Calls to
  35. :meth:`Executor.submit` and :meth:`Executor.map` made after shutdown will
  36. raise :exc:`RuntimeError`.
  37. If *wait* is `True` then this method will not return until all the pending
  38. futures are done executing and the resources associated with the executor
  39. have been freed. If *wait* is `False` then this method will return
  40. immediately and the resources associated with the executor will be freed
  41. when all pending futures are done executing. Regardless of the value of
  42. *wait*, the entire Python program will not exit until all pending futures
  43. are done executing.
  44. You can avoid having to call this method explicitly if you use the `with`
  45. statement, which will shutdown the `Executor` (waiting as if
  46. `Executor.shutdown` were called with *wait* set to `True`):
  47. ::
  48. import shutil
  49. with ThreadPoolExecutor(max_workers=4) as e:
  50. e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
  51. e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
  52. e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
  53. e.submit(shutil.copy, 'src3.txt', 'dest4.txt')
  54. ThreadPoolExecutor Objects
  55. --------------------------
  56. The :class:`ThreadPoolExecutor` class is an :class:`Executor` subclass that uses
  57. a pool of threads to execute calls asynchronously.
  58. Deadlock can occur when the callable associated with a :class:`Future` waits on
  59. the results of another :class:`Future`. For example:
  60. ::
  61. import time
  62. def wait_on_b():
  63. time.sleep(5)
  64. print(b.result()) # b will never complete because it is waiting on a.
  65. return 5
  66. def wait_on_a():
  67. time.sleep(5)
  68. print(a.result()) # a will never complete because it is waiting on b.
  69. return 6
  70. executor = ThreadPoolExecutor(max_workers=2)
  71. a = executor.submit(wait_on_b)
  72. b = executor.submit(wait_on_a)
  73. And:
  74. ::
  75. def wait_on_future():
  76. f = executor.submit(pow, 5, 2)
  77. # This will never complete because there is only one worker thread and
  78. # it is executing this function.
  79. print(f.result())
  80. executor = ThreadPoolExecutor(max_workers=1)
  81. executor.submit(wait_on_future)
  82. .. class:: ThreadPoolExecutor(max_workers)
  83. Executes calls asynchronously using at pool of at most *max_workers* threads.
  84. .. _threadpoolexecutor-example:
  85. ThreadPoolExecutor Example
  86. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  87. ::
  88. from concurrent import futures
  89. import urllib.request
  90. URLS = ['http://www.foxnews.com/',
  91. 'http://www.cnn.com/',
  92. 'http://europe.wsj.com/',
  93. 'http://www.bbc.co.uk/',
  94. 'http://some-made-up-domain.com/']
  95. def load_url(url, timeout):
  96. return urllib.request.urlopen(url, timeout=timeout).read()
  97. with futures.ThreadPoolExecutor(max_workers=5) as executor:
  98. future_to_url = dict((executor.submit(load_url, url, 60), url)
  99. for url in URLS)
  100. for future in futures.as_completed(future_to_url):
  101. url = future_to_url[future]
  102. if future.exception() is not None:
  103. print('%r generated an exception: %s' % (url,
  104. future.exception()))
  105. else:
  106. print('%r page is %d bytes' % (url, len(future.result())))
  107. ProcessPoolExecutor Objects
  108. ---------------------------
  109. The :class:`ProcessPoolExecutor` class is an :class:`Executor` subclass that
  110. uses a pool of processes to execute calls asynchronously.
  111. :class:`ProcessPoolExecutor` uses the :mod:`multiprocessing` module, which
  112. allows it to side-step the :term:`Global Interpreter Lock` but also means that
  113. only picklable objects can be executed and returned.
  114. Calling :class:`Executor` or :class:`Future` methods from a callable submitted
  115. to a :class:`ProcessPoolExecutor` will result in deadlock.
  116. .. class:: ProcessPoolExecutor(max_workers=None)
  117. Executes calls asynchronously using a pool of at most *max_workers*
  118. processes. If *max_workers* is ``None`` or not given then as many worker
  119. processes will be created as the machine has processors.
  120. .. _processpoolexecutor-example:
  121. ProcessPoolExecutor Example
  122. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  123. ::
  124. import math
  125. PRIMES = [
  126. 112272535095293,
  127. 112582705942171,
  128. 112272535095293,
  129. 115280095190773,
  130. 115797848077099,
  131. 1099726899285419]
  132. def is_prime(n):
  133. if n % 2 == 0:
  134. return False
  135. sqrt_n = int(math.floor(math.sqrt(n)))
  136. for i in range(3, sqrt_n + 1, 2):
  137. if n % i == 0:
  138. return False
  139. return True
  140. def main():
  141. with futures.ProcessPoolExecutor() as executor:
  142. for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
  143. print('%d is prime: %s' % (number, prime))
  144. if __name__ == '__main__':
  145. main()
  146. Future Objects
  147. --------------
  148. The :class:`Future` class encapulates the asynchronous execution of a callable.
  149. :class:`Future` instances are created by :meth:`Executor.submit`.
  150. .. method:: Future.cancel()
  151. Attempt to cancel the call. If the call is currently being executed then
  152. it cannot be cancelled and the method will return `False`, otherwise the call
  153. will be cancelled and the method will return `True`.
  154. .. method:: Future.cancelled()
  155. Return `True` if the call was successfully cancelled.
  156. .. method:: Future.running()
  157. Return `True` if the call is currently being executed and cannot be
  158. cancelled.
  159. .. method:: Future.done()
  160. Return `True` if the call was successfully cancelled or finished running.
  161. .. method:: Future.result(timeout=None)
  162. Return the value returned by the call. If the call hasn't yet completed then
  163. this method will wait up to *timeout* seconds. If the call hasn't completed
  164. in *timeout* seconds then a :exc:`TimeoutError` will be raised. *timeout* can
  165. be an int or float.If *timeout* is not specified or ``None`` then there is no
  166. limit to the wait time.
  167. If the future is cancelled before completing then :exc:`CancelledError` will
  168. be raised.
  169. If the call raised then this method will raise the same exception.
  170. .. method:: Future.exception(timeout=None)
  171. Return the exception raised by the call. If the call hasn't yet completed
  172. then this method will wait up to *timeout* seconds. If the call hasn't
  173. completed in *timeout* seconds then a :exc:`TimeoutError` will be raised.
  174. *timeout* can be an int or float. If *timeout* is not specified or ``None``
  175. then there is no limit to the wait time.
  176. If the future is cancelled before completing then :exc:`CancelledError` will
  177. be raised.
  178. If the call completed without raising then ``None`` is returned.
  179. .. method:: Future.add_done_callback(fn)
  180. Attaches the callable *fn* to the future. *fn* will be called, with the
  181. future as its only argument, when the future is cancelled or finishes
  182. running.
  183. Added callables are called in the order that they were added and are always
  184. called in a thread belonging to the process that added them. If the callable
  185. raises an :exc:`Exception` then it will be logged and ignored. If the
  186. callable raises another :exc:`BaseException` then the behavior is not
  187. defined.
  188. If the future has already completed or been cancelled then *fn* will be
  189. called immediately.
  190. Internal Future Methods
  191. ^^^^^^^^^^^^^^^^^^^^^^^
  192. The following :class:`Future` methods are meant for use in unit tests and
  193. :class:`Executor` implementations.
  194. .. method:: Future.set_running_or_notify_cancel()
  195. This method should only be called by :class:`Executor` implementations before
  196. executing the work associated with the :class:`Future` and by unit tests.
  197. If the method returns `False` then the :class:`Future` was cancelled i.e.
  198. :meth:`Future.cancel` was called and returned `True`. Any threads waiting
  199. on the :class:`Future` completing (i.e. through :func:`as_completed` or
  200. :func:`wait`) will be woken up.
  201. If the method returns `True` then the :class:`Future` was not cancelled
  202. and has been put in the running state i.e. calls to
  203. :meth:`Future.running` will return `True`.
  204. This method can only be called once and cannot be called after
  205. :meth:`Future.set_result` or :meth:`Future.set_exception` have been
  206. called.
  207. .. method:: Future.set_result(result)
  208. Sets the result of the work associated with the :class:`Future` to *result*.
  209. This method should only be used by Executor implementations and unit tests.
  210. .. method:: Future.set_exception(exception)
  211. Sets the result of the work associated with the :class:`Future` to the
  212. :class:`Exception` *exception*.
  213. This method should only be used by Executor implementations and unit tests.
  214. Module Functions
  215. ----------------
  216. .. function:: wait(fs, timeout=None, return_when=ALL_COMPLETED)
  217. Wait for the :class:`Future` instances (possibly created by different
  218. :class:`Executor` instances) given by *fs* to complete. Returns a named
  219. 2-tuple of sets. The first set, named "done", contains the futures that
  220. completed (finished or were cancelled) before the wait completed. The second
  221. set, named "not_done", contains uncompleted futures.
  222. *timeout* can be used to control the maximum number of seconds to wait before
  223. returning. *timeout* can be an int or float. If *timeout* is not specified or
  224. ``None`` then there is no limit to the wait time.
  225. *return_when* indicates when this function should return. It must be one of
  226. the following constants:
  227. +-----------------------------+----------------------------------------+
  228. | Constant | Description |
  229. +=============================+========================================+
  230. | :const:`FIRST_COMPLETED` | The function will return when any |
  231. | | future finishes or is cancelled. |
  232. +-----------------------------+----------------------------------------+
  233. | :const:`FIRST_EXCEPTION` | The function will return when any |
  234. | | future finishes by raising an |
  235. | | exception. If no future raises an |
  236. | | exception then it is equivalent to |
  237. | | `ALL_COMPLETED`. |
  238. +-----------------------------+----------------------------------------+
  239. | :const:`ALL_COMPLETED` | The function will return when all |
  240. | | futures finish or are cancelled. |
  241. +-----------------------------+----------------------------------------+
  242. .. function:: as_completed(fs, timeout=None)
  243. Returns an iterator over the :class:`Future` instances (possibly created
  244. by different :class:`Executor` instances) given by *fs* that yields futures
  245. as they complete (finished or were cancelled). Any futures that completed
  246. before :func:`as_completed()` was called will be yielded first. The returned
  247. iterator raises a :exc:`TimeoutError` if :meth:`__next__()` is called and
  248. the result isn't available after *timeout* seconds from the original call
  249. to :func:`as_completed()`. *timeout* can be an int or float. If *timeout*
  250. is not specified or ``None`` then there is no limit to the wait time.