_base.py 19 KB

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