_base.py 20 KB

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