_base.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. __author__ = 'Brian Quinlan (brian@sweetapp.com)'
  4. import collections
  5. import logging
  6. import threading
  7. import time
  8. import types
  9. FIRST_COMPLETED = 'FIRST_COMPLETED'
  10. FIRST_EXCEPTION = 'FIRST_EXCEPTION'
  11. ALL_COMPLETED = 'ALL_COMPLETED'
  12. _AS_COMPLETED = '_AS_COMPLETED'
  13. # Possible future states (for internal use by the futures package).
  14. PENDING = 'PENDING'
  15. RUNNING = 'RUNNING'
  16. # The future was cancelled by the user...
  17. CANCELLED = 'CANCELLED'
  18. # ...and _Waiter.add_cancelled() was called by a worker.
  19. CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
  20. FINISHED = 'FINISHED'
  21. _FUTURE_STATES = [
  22. PENDING,
  23. RUNNING,
  24. CANCELLED,
  25. CANCELLED_AND_NOTIFIED,
  26. FINISHED
  27. ]
  28. _STATE_TO_DESCRIPTION_MAP = {
  29. PENDING: "pending",
  30. RUNNING: "running",
  31. CANCELLED: "cancelled",
  32. CANCELLED_AND_NOTIFIED: "cancelled",
  33. FINISHED: "finished"
  34. }
  35. # Logger for internal use by the futures package.
  36. LOGGER = logging.getLogger("concurrent.futures")
  37. class Error(Exception):
  38. """Base class for all future-related exceptions."""
  39. pass
  40. class CancelledError(Error):
  41. """The Future was cancelled."""
  42. pass
  43. TimeoutError = TimeoutError # make local alias for the standard exception
  44. class InvalidStateError(Error):
  45. """The operation is not allowed in this state."""
  46. pass
  47. class _Waiter(object):
  48. """Provides the event that wait() and as_completed() block on."""
  49. def __init__(self):
  50. self.event = threading.Event()
  51. self.finished_futures = []
  52. def add_result(self, future):
  53. self.finished_futures.append(future)
  54. def add_exception(self, future):
  55. self.finished_futures.append(future)
  56. def add_cancelled(self, future):
  57. self.finished_futures.append(future)
  58. class _AsCompletedWaiter(_Waiter):
  59. """Used by as_completed()."""
  60. def __init__(self):
  61. super(_AsCompletedWaiter, self).__init__()
  62. self.lock = threading.Lock()
  63. def add_result(self, future):
  64. with self.lock:
  65. super(_AsCompletedWaiter, self).add_result(future)
  66. self.event.set()
  67. def add_exception(self, future):
  68. with self.lock:
  69. super(_AsCompletedWaiter, self).add_exception(future)
  70. self.event.set()
  71. def add_cancelled(self, future):
  72. with self.lock:
  73. super(_AsCompletedWaiter, self).add_cancelled(future)
  74. self.event.set()
  75. class _FirstCompletedWaiter(_Waiter):
  76. """Used by wait(return_when=FIRST_COMPLETED)."""
  77. def add_result(self, future):
  78. super().add_result(future)
  79. self.event.set()
  80. def add_exception(self, future):
  81. super().add_exception(future)
  82. self.event.set()
  83. def add_cancelled(self, future):
  84. super().add_cancelled(future)
  85. self.event.set()
  86. class _AllCompletedWaiter(_Waiter):
  87. """Used by wait(return_when=FIRST_EXCEPTION and ALL_COMPLETED)."""
  88. def __init__(self, num_pending_calls, stop_on_exception):
  89. self.num_pending_calls = num_pending_calls
  90. self.stop_on_exception = stop_on_exception
  91. self.lock = threading.Lock()
  92. super().__init__()
  93. def _decrement_pending_calls(self):
  94. with self.lock:
  95. self.num_pending_calls -= 1
  96. if not self.num_pending_calls:
  97. self.event.set()
  98. def add_result(self, future):
  99. super().add_result(future)
  100. self._decrement_pending_calls()
  101. def add_exception(self, future):
  102. super().add_exception(future)
  103. if self.stop_on_exception:
  104. self.event.set()
  105. else:
  106. self._decrement_pending_calls()
  107. def add_cancelled(self, future):
  108. super().add_cancelled(future)
  109. self._decrement_pending_calls()
  110. class _AcquireFutures(object):
  111. """A context manager that does an ordered acquire of Future conditions."""
  112. def __init__(self, futures):
  113. self.futures = sorted(futures, key=id)
  114. def __enter__(self):
  115. for future in self.futures:
  116. future._condition.acquire()
  117. def __exit__(self, *args):
  118. for future in self.futures:
  119. future._condition.release()
  120. def _create_and_install_waiters(fs, return_when):
  121. if return_when == _AS_COMPLETED:
  122. waiter = _AsCompletedWaiter()
  123. elif return_when == FIRST_COMPLETED:
  124. waiter = _FirstCompletedWaiter()
  125. else:
  126. pending_count = sum(
  127. f._state not in [CANCELLED_AND_NOTIFIED, FINISHED] for f in fs)
  128. if return_when == FIRST_EXCEPTION:
  129. waiter = _AllCompletedWaiter(pending_count, stop_on_exception=True)
  130. elif return_when == ALL_COMPLETED:
  131. waiter = _AllCompletedWaiter(pending_count, stop_on_exception=False)
  132. else:
  133. raise ValueError("Invalid return condition: %r" % return_when)
  134. for f in fs:
  135. f._waiters.append(waiter)
  136. return waiter
  137. def _yield_finished_futures(fs, waiter, ref_collect):
  138. """
  139. Iterate on the list *fs*, yielding finished futures one by one in
  140. reverse order.
  141. Before yielding a future, *waiter* is removed from its waiters
  142. and the future is removed from each set in the collection of sets
  143. *ref_collect*.
  144. The aim of this function is to avoid keeping stale references after
  145. the future is yielded and before the iterator resumes.
  146. """
  147. while fs:
  148. f = fs[-1]
  149. for futures_set in ref_collect:
  150. futures_set.remove(f)
  151. with f._condition:
  152. f._waiters.remove(waiter)
  153. del f
  154. # Careful not to keep a reference to the popped value
  155. yield fs.pop()
  156. def as_completed(fs, timeout=None):
  157. """An iterator over the given futures that yields each as it completes.
  158. Args:
  159. fs: The sequence of Futures (possibly created by different Executors) to
  160. iterate over.
  161. timeout: The maximum number of seconds to wait. If None, then there
  162. is no limit on the wait time.
  163. Returns:
  164. An iterator that yields the given Futures as they complete (finished or
  165. cancelled). If any given Futures are duplicated, they will be returned
  166. once.
  167. Raises:
  168. TimeoutError: If the entire result iterator could not be generated
  169. before the given timeout.
  170. """
  171. if timeout is not None:
  172. end_time = timeout + time.monotonic()
  173. fs = set(fs)
  174. total_futures = len(fs)
  175. with _AcquireFutures(fs):
  176. finished = set(
  177. f for f in fs
  178. if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
  179. pending = fs - finished
  180. waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
  181. finished = list(finished)
  182. try:
  183. yield from _yield_finished_futures(finished, waiter,
  184. ref_collect=(fs,))
  185. while pending:
  186. if timeout is None:
  187. wait_timeout = None
  188. else:
  189. wait_timeout = end_time - time.monotonic()
  190. if wait_timeout < 0:
  191. raise TimeoutError(
  192. '%d (of %d) futures unfinished' % (
  193. len(pending), total_futures))
  194. waiter.event.wait(wait_timeout)
  195. with waiter.lock:
  196. finished = waiter.finished_futures
  197. waiter.finished_futures = []
  198. waiter.event.clear()
  199. # reverse to keep finishing order
  200. finished.reverse()
  201. yield from _yield_finished_futures(finished, waiter,
  202. ref_collect=(fs, pending))
  203. finally:
  204. # Remove waiter from unfinished futures
  205. for f in fs:
  206. with f._condition:
  207. f._waiters.remove(waiter)
  208. DoneAndNotDoneFutures = collections.namedtuple(
  209. 'DoneAndNotDoneFutures', 'done not_done')
  210. def wait(fs, timeout=None, return_when=ALL_COMPLETED):
  211. """Wait for the futures in the given sequence to complete.
  212. Args:
  213. fs: The sequence of Futures (possibly created by different Executors) to
  214. wait upon.
  215. timeout: The maximum number of seconds to wait. If None, then there
  216. is no limit on the wait time.
  217. return_when: Indicates when this function should return. The options
  218. are:
  219. FIRST_COMPLETED - Return when any future finishes or is
  220. cancelled.
  221. FIRST_EXCEPTION - Return when any future finishes by raising an
  222. exception. If no future raises an exception
  223. then it is equivalent to ALL_COMPLETED.
  224. ALL_COMPLETED - Return when all futures finish or are cancelled.
  225. Returns:
  226. A named 2-tuple of sets. The first set, named 'done', contains the
  227. futures that completed (is finished or cancelled) before the wait
  228. completed. The second set, named 'not_done', contains uncompleted
  229. futures. Duplicate futures given to *fs* are removed and will be
  230. returned only once.
  231. """
  232. fs = set(fs)
  233. with _AcquireFutures(fs):
  234. done = {f for f in fs
  235. if f._state in [CANCELLED_AND_NOTIFIED, FINISHED]}
  236. not_done = fs - done
  237. if (return_when == FIRST_COMPLETED) and done:
  238. return DoneAndNotDoneFutures(done, not_done)
  239. elif (return_when == FIRST_EXCEPTION) and done:
  240. if any(f for f in done
  241. if not f.cancelled() and f.exception() is not None):
  242. return DoneAndNotDoneFutures(done, not_done)
  243. if len(done) == len(fs):
  244. return DoneAndNotDoneFutures(done, not_done)
  245. waiter = _create_and_install_waiters(fs, return_when)
  246. waiter.event.wait(timeout)
  247. for f in fs:
  248. with f._condition:
  249. f._waiters.remove(waiter)
  250. done.update(waiter.finished_futures)
  251. return DoneAndNotDoneFutures(done, fs - done)
  252. def _result_or_cancel(fut, timeout=None):
  253. try:
  254. try:
  255. return fut.result(timeout)
  256. finally:
  257. fut.cancel()
  258. finally:
  259. # Break a reference cycle with the exception in self._exception
  260. del fut
  261. class Future(object):
  262. """Represents the result of an asynchronous computation."""
  263. def __init__(self):
  264. """Initializes the future. Should not be called by clients."""
  265. self._condition = threading.Condition()
  266. self._state = PENDING
  267. self._result = None
  268. self._exception = None
  269. self._waiters = []
  270. self._done_callbacks = []
  271. def _invoke_callbacks(self):
  272. for callback in self._done_callbacks:
  273. try:
  274. callback(self)
  275. except Exception:
  276. LOGGER.exception('exception calling callback for %r', self)
  277. def __repr__(self):
  278. with self._condition:
  279. if self._state == FINISHED:
  280. if self._exception:
  281. return '<%s at %#x state=%s raised %s>' % (
  282. self.__class__.__name__,
  283. id(self),
  284. _STATE_TO_DESCRIPTION_MAP[self._state],
  285. self._exception.__class__.__name__)
  286. else:
  287. return '<%s at %#x state=%s returned %s>' % (
  288. self.__class__.__name__,
  289. id(self),
  290. _STATE_TO_DESCRIPTION_MAP[self._state],
  291. self._result.__class__.__name__)
  292. return '<%s at %#x state=%s>' % (
  293. self.__class__.__name__,
  294. id(self),
  295. _STATE_TO_DESCRIPTION_MAP[self._state])
  296. def cancel(self):
  297. """Cancel the future if possible.
  298. Returns True if the future was cancelled, False otherwise. A future
  299. cannot be cancelled if it is running or has already completed.
  300. """
  301. with self._condition:
  302. if self._state in [RUNNING, FINISHED]:
  303. return False
  304. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  305. return True
  306. self._state = CANCELLED
  307. self._condition.notify_all()
  308. self._invoke_callbacks()
  309. return True
  310. def cancelled(self):
  311. """Return True if the future was cancelled."""
  312. with self._condition:
  313. return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]
  314. def running(self):
  315. """Return True if the future is currently executing."""
  316. with self._condition:
  317. return self._state == RUNNING
  318. def done(self):
  319. """Return True if the future was cancelled or finished executing."""
  320. with self._condition:
  321. return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]
  322. def __get_result(self):
  323. if self._exception:
  324. try:
  325. raise self._exception
  326. finally:
  327. # Break a reference cycle with the exception in self._exception
  328. self = None
  329. else:
  330. return self._result
  331. def add_done_callback(self, fn):
  332. """Attaches a callable that will be called when the future finishes.
  333. Args:
  334. fn: A callable that will be called with this future as its only
  335. argument when the future completes or is cancelled. The callable
  336. will always be called by a thread in the same process in which
  337. it was added. If the future has already completed or been
  338. cancelled then the callable will be called immediately. These
  339. callables are called in the order that they were added.
  340. """
  341. with self._condition:
  342. if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
  343. self._done_callbacks.append(fn)
  344. return
  345. try:
  346. fn(self)
  347. except Exception:
  348. LOGGER.exception('exception calling callback for %r', self)
  349. def result(self, timeout=None):
  350. """Return the result of the call that the future represents.
  351. Args:
  352. timeout: The number of seconds to wait for the result if the future
  353. isn't done. If None, then there is no limit on the wait time.
  354. Returns:
  355. The result of the call that the future represents.
  356. Raises:
  357. CancelledError: If the future was cancelled.
  358. TimeoutError: If the future didn't finish executing before the given
  359. timeout.
  360. Exception: If the call raised then that exception will be raised.
  361. """
  362. try:
  363. with self._condition:
  364. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  365. raise CancelledError()
  366. elif self._state == FINISHED:
  367. return self.__get_result()
  368. self._condition.wait(timeout)
  369. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  370. raise CancelledError()
  371. elif self._state == FINISHED:
  372. return self.__get_result()
  373. else:
  374. raise TimeoutError()
  375. finally:
  376. # Break a reference cycle with the exception in self._exception
  377. self = None
  378. def exception(self, timeout=None):
  379. """Return the exception raised by the call that the future represents.
  380. Args:
  381. timeout: The number of seconds to wait for the exception if the
  382. future isn't done. If None, then there is no limit on the wait
  383. time.
  384. Returns:
  385. The exception raised by the call that the future represents or None
  386. if the call completed without raising.
  387. Raises:
  388. CancelledError: If the future was cancelled.
  389. TimeoutError: If the future didn't finish executing before the given
  390. timeout.
  391. """
  392. with self._condition:
  393. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  394. raise CancelledError()
  395. elif self._state == FINISHED:
  396. return self._exception
  397. self._condition.wait(timeout)
  398. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  399. raise CancelledError()
  400. elif self._state == FINISHED:
  401. return self._exception
  402. else:
  403. raise TimeoutError()
  404. # The following methods should only be used by Executors and in tests.
  405. def set_running_or_notify_cancel(self):
  406. """Mark the future as running or process any cancel notifications.
  407. Should only be used by Executor implementations and unit tests.
  408. If the future has been cancelled (cancel() was called and returned
  409. True) then any threads waiting on the future completing (though calls
  410. to as_completed() or wait()) are notified and False is returned.
  411. If the future was not cancelled then it is put in the running state
  412. (future calls to running() will return True) and True is returned.
  413. This method should be called by Executor implementations before
  414. executing the work associated with this future. If this method returns
  415. False then the work should not be executed.
  416. Returns:
  417. False if the Future was cancelled, True otherwise.
  418. Raises:
  419. RuntimeError: if this method was already called or if set_result()
  420. or set_exception() was called.
  421. """
  422. with self._condition:
  423. if self._state == CANCELLED:
  424. self._state = CANCELLED_AND_NOTIFIED
  425. for waiter in self._waiters:
  426. waiter.add_cancelled(self)
  427. # self._condition.notify_all() is not necessary because
  428. # self.cancel() triggers a notification.
  429. return False
  430. elif self._state == PENDING:
  431. self._state = RUNNING
  432. return True
  433. else:
  434. LOGGER.critical('Future %s in unexpected state: %s',
  435. id(self),
  436. self._state)
  437. raise RuntimeError('Future in unexpected state')
  438. def set_result(self, result):
  439. """Sets the return value of work associated with the future.
  440. Should only be used by Executor implementations and unit tests.
  441. """
  442. with self._condition:
  443. if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
  444. raise InvalidStateError('{}: {!r}'.format(self._state, self))
  445. self._result = result
  446. self._state = FINISHED
  447. for waiter in self._waiters:
  448. waiter.add_result(self)
  449. self._condition.notify_all()
  450. self._invoke_callbacks()
  451. def set_exception(self, exception):
  452. """Sets the result of the future as being the given exception.
  453. Should only be used by Executor implementations and unit tests.
  454. """
  455. with self._condition:
  456. if self._state in {CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED}:
  457. raise InvalidStateError('{}: {!r}'.format(self._state, self))
  458. self._exception = exception
  459. self._state = FINISHED
  460. for waiter in self._waiters:
  461. waiter.add_exception(self)
  462. self._condition.notify_all()
  463. self._invoke_callbacks()
  464. __class_getitem__ = classmethod(types.GenericAlias)
  465. class Executor(object):
  466. """This is an abstract base class for concrete asynchronous executors."""
  467. def submit(self, fn, /, *args, **kwargs):
  468. """Submits a callable to be executed with the given arguments.
  469. Schedules the callable to be executed as fn(*args, **kwargs) and returns
  470. a Future instance representing the execution of the callable.
  471. Returns:
  472. A Future representing the given call.
  473. """
  474. raise NotImplementedError()
  475. def map(self, fn, *iterables, timeout=None, chunksize=1):
  476. """Returns an iterator equivalent to map(fn, iter).
  477. Args:
  478. fn: A callable that will take as many arguments as there are
  479. passed iterables.
  480. timeout: The maximum number of seconds to wait. If None, then there
  481. is no limit on the wait time.
  482. chunksize: The size of the chunks the iterable will be broken into
  483. before being passed to a child process. This argument is only
  484. used by ProcessPoolExecutor; it is ignored by
  485. ThreadPoolExecutor.
  486. Returns:
  487. An iterator equivalent to: map(func, *iterables) but the calls may
  488. be evaluated out-of-order.
  489. Raises:
  490. TimeoutError: If the entire result iterator could not be generated
  491. before the given timeout.
  492. Exception: If fn(*args) raises for any values.
  493. """
  494. if timeout is not None:
  495. end_time = timeout + time.monotonic()
  496. fs = [self.submit(fn, *args) for args in zip(*iterables)]
  497. # Yield must be hidden in closure so that the futures are submitted
  498. # before the first iterator value is required.
  499. def result_iterator():
  500. try:
  501. # reverse to keep finishing order
  502. fs.reverse()
  503. while fs:
  504. # Careful not to keep a reference to the popped future
  505. if timeout is None:
  506. yield _result_or_cancel(fs.pop())
  507. else:
  508. yield _result_or_cancel(fs.pop(), end_time - time.monotonic())
  509. finally:
  510. for future in fs:
  511. future.cancel()
  512. return result_iterator()
  513. def shutdown(self, wait=True, *, cancel_futures=False):
  514. """Clean-up the resources associated with the Executor.
  515. It is safe to call this method several times. Otherwise, no other
  516. methods can be called after this one.
  517. Args:
  518. wait: If True then shutdown will not return until all running
  519. futures have finished executing and the resources used by the
  520. executor have been reclaimed.
  521. cancel_futures: If True then shutdown will cancel all pending
  522. futures. Futures that are completed or running will not be
  523. cancelled.
  524. """
  525. pass
  526. def __enter__(self):
  527. return self
  528. def __exit__(self, exc_type, exc_val, exc_tb):
  529. self.shutdown(wait=True)
  530. return False
  531. class BrokenExecutor(RuntimeError):
  532. """
  533. Raised when a executor has become non-functional after a severe failure.
  534. """