_base.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. # Copyright 2009 Brian Quinlan. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. import collections
  4. import logging
  5. import threading
  6. import itertools
  7. import time
  8. import types
  9. __author__ = 'Brian Quinlan (brian@sweetapp.com)'
  10. FIRST_COMPLETED = 'FIRST_COMPLETED'
  11. FIRST_EXCEPTION = 'FIRST_EXCEPTION'
  12. ALL_COMPLETED = 'ALL_COMPLETED'
  13. _AS_COMPLETED = '_AS_COMPLETED'
  14. # Possible future states (for internal use by the futures package).
  15. PENDING = 'PENDING'
  16. RUNNING = 'RUNNING'
  17. # The future was cancelled by the user...
  18. CANCELLED = 'CANCELLED'
  19. # ...and _Waiter.add_cancelled() was called by a worker.
  20. CANCELLED_AND_NOTIFIED = 'CANCELLED_AND_NOTIFIED'
  21. FINISHED = 'FINISHED'
  22. _FUTURE_STATES = [
  23. PENDING,
  24. RUNNING,
  25. CANCELLED,
  26. CANCELLED_AND_NOTIFIED,
  27. FINISHED
  28. ]
  29. _STATE_TO_DESCRIPTION_MAP = {
  30. PENDING: "pending",
  31. RUNNING: "running",
  32. CANCELLED: "cancelled",
  33. CANCELLED_AND_NOTIFIED: "cancelled",
  34. FINISHED: "finished"
  35. }
  36. # Logger for internal use by the futures package.
  37. LOGGER = logging.getLogger("concurrent.futures")
  38. class Error(Exception):
  39. """Base class for all future-related exceptions."""
  40. pass
  41. class CancelledError(Error):
  42. """The Future was cancelled."""
  43. pass
  44. class TimeoutError(Error):
  45. """The operation exceeded the given deadline."""
  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(_FirstCompletedWaiter, self).add_result(future)
  79. self.event.set()
  80. def add_exception(self, future):
  81. super(_FirstCompletedWaiter, self).add_exception(future)
  82. self.event.set()
  83. def add_cancelled(self, future):
  84. super(_FirstCompletedWaiter, self).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(_AllCompletedWaiter, self).__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(_AllCompletedWaiter, self).add_result(future)
  100. self._decrement_pending_calls()
  101. def add_exception(self, future):
  102. super(_AllCompletedWaiter, self).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(_AllCompletedWaiter, self).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.time()
  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. for f in _yield_finished_futures(finished, waiter,
  184. ref_collect=(fs,)):
  185. f = [f]
  186. yield f.pop()
  187. while pending:
  188. if timeout is None:
  189. wait_timeout = None
  190. else:
  191. wait_timeout = end_time - time.time()
  192. if wait_timeout < 0:
  193. raise TimeoutError(
  194. '%d (of %d) futures unfinished' % (
  195. len(pending), total_futures))
  196. waiter.event.wait(wait_timeout)
  197. with waiter.lock:
  198. finished = waiter.finished_futures
  199. waiter.finished_futures = []
  200. waiter.event.clear()
  201. # reverse to keep finishing order
  202. finished.reverse()
  203. for f in _yield_finished_futures(finished, waiter,
  204. ref_collect=(fs, pending)):
  205. f = [f]
  206. yield f.pop()
  207. finally:
  208. # Remove waiter from unfinished futures
  209. for f in fs:
  210. with f._condition:
  211. f._waiters.remove(waiter)
  212. DoneAndNotDoneFutures = collections.namedtuple(
  213. 'DoneAndNotDoneFutures', 'done not_done')
  214. def wait(fs, timeout=None, return_when=ALL_COMPLETED):
  215. """Wait for the futures in the given sequence to complete.
  216. Args:
  217. fs: The sequence of Futures (possibly created by different Executors) to
  218. wait upon.
  219. timeout: The maximum number of seconds to wait. If None, then there
  220. is no limit on the wait time.
  221. return_when: Indicates when this function should return. The options
  222. are:
  223. FIRST_COMPLETED - Return when any future finishes or is
  224. cancelled.
  225. FIRST_EXCEPTION - Return when any future finishes by raising an
  226. exception. If no future raises an exception
  227. then it is equivalent to ALL_COMPLETED.
  228. ALL_COMPLETED - Return when all futures finish or are cancelled.
  229. Returns:
  230. A named 2-tuple of sets. The first set, named 'done', contains the
  231. futures that completed (is finished or cancelled) before the wait
  232. completed. The second set, named 'not_done', contains uncompleted
  233. futures.
  234. """
  235. with _AcquireFutures(fs):
  236. done = set(f for f in fs
  237. if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
  238. not_done = set(fs) - done
  239. if (return_when == FIRST_COMPLETED) and done:
  240. return DoneAndNotDoneFutures(done, not_done)
  241. elif (return_when == FIRST_EXCEPTION) and done:
  242. if any(f for f in done
  243. if not f.cancelled() and f.exception() is not None):
  244. return DoneAndNotDoneFutures(done, not_done)
  245. if len(done) == len(fs):
  246. return DoneAndNotDoneFutures(done, not_done)
  247. waiter = _create_and_install_waiters(fs, return_when)
  248. waiter.event.wait(timeout)
  249. for f in fs:
  250. with f._condition:
  251. f._waiters.remove(waiter)
  252. done.update(waiter.finished_futures)
  253. return DoneAndNotDoneFutures(done, set(fs) - done)
  254. class Future(object):
  255. """Represents the result of an asynchronous computation."""
  256. def __init__(self):
  257. """Initializes the future. Should not be called by clients."""
  258. self._condition = threading.Condition()
  259. self._state = PENDING
  260. self._result = None
  261. self._exception = None
  262. self._traceback = None
  263. self._waiters = []
  264. self._done_callbacks = []
  265. def _invoke_callbacks(self):
  266. for callback in self._done_callbacks:
  267. try:
  268. callback(self)
  269. except Exception:
  270. LOGGER.exception('exception calling callback for %r', self)
  271. except BaseException:
  272. # Explicitly let all other new-style exceptions through so
  273. # that we can catch all old-style exceptions with a simple
  274. # "except:" clause below.
  275. #
  276. # All old-style exception objects are instances of
  277. # types.InstanceType, but "except types.InstanceType:" does
  278. # not catch old-style exceptions for some reason. Thus, the
  279. # only way to catch all old-style exceptions without catching
  280. # any new-style exceptions is to filter out the new-style
  281. # exceptions, which all derive from BaseException.
  282. raise
  283. except:
  284. # Because of the BaseException clause above, this handler only
  285. # executes for old-style exception objects.
  286. LOGGER.exception('exception calling callback for %r', self)
  287. def __repr__(self):
  288. with self._condition:
  289. if self._state == FINISHED:
  290. if self._exception:
  291. return '<%s at %#x state=%s raised %s>' % (
  292. self.__class__.__name__,
  293. id(self),
  294. _STATE_TO_DESCRIPTION_MAP[self._state],
  295. self._exception.__class__.__name__)
  296. else:
  297. return '<%s at %#x state=%s returned %s>' % (
  298. self.__class__.__name__,
  299. id(self),
  300. _STATE_TO_DESCRIPTION_MAP[self._state],
  301. self._result.__class__.__name__)
  302. return '<%s at %#x state=%s>' % (
  303. self.__class__.__name__,
  304. id(self),
  305. _STATE_TO_DESCRIPTION_MAP[self._state])
  306. def cancel(self):
  307. """Cancel the future if possible.
  308. Returns True if the future was cancelled, False otherwise. A future
  309. cannot be cancelled if it is running or has already completed.
  310. """
  311. with self._condition:
  312. if self._state in [RUNNING, FINISHED]:
  313. return False
  314. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  315. return True
  316. self._state = CANCELLED
  317. self._condition.notify_all()
  318. self._invoke_callbacks()
  319. return True
  320. def cancelled(self):
  321. """Return True if the future was cancelled."""
  322. with self._condition:
  323. return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]
  324. def running(self):
  325. """Return True if the future is currently executing."""
  326. with self._condition:
  327. return self._state == RUNNING
  328. def done(self):
  329. """Return True of the future was cancelled or finished executing."""
  330. with self._condition:
  331. return self._state in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]
  332. def __get_result(self):
  333. if self._exception:
  334. if isinstance(self._exception, types.InstanceType):
  335. # The exception is an instance of an old-style class, which
  336. # means type(self._exception) returns types.ClassType instead
  337. # of the exception's actual class type.
  338. exception_type = self._exception.__class__
  339. else:
  340. exception_type = type(self._exception)
  341. raise exception_type, self._exception, self._traceback
  342. else:
  343. return self._result
  344. def add_done_callback(self, fn):
  345. """Attaches a callable that will be called when the future finishes.
  346. Args:
  347. fn: A callable that will be called with this future as its only
  348. argument when the future completes or is cancelled. The callable
  349. will always be called by a thread in the same process in which
  350. it was added. If the future has already completed or been
  351. cancelled then the callable will be called immediately. These
  352. callables are called in the order that they were added.
  353. """
  354. with self._condition:
  355. if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
  356. self._done_callbacks.append(fn)
  357. return
  358. fn(self)
  359. def result(self, timeout=None):
  360. """Return the result of the call that the future represents.
  361. Args:
  362. timeout: The number of seconds to wait for the result if the future
  363. isn't done. If None, then there is no limit on the wait time.
  364. Returns:
  365. The result of the call that the future represents.
  366. Raises:
  367. CancelledError: If the future was cancelled.
  368. TimeoutError: If the future didn't finish executing before the given
  369. timeout.
  370. Exception: If the call raised then that exception will be raised.
  371. """
  372. with self._condition:
  373. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  374. raise CancelledError()
  375. elif self._state == FINISHED:
  376. return self.__get_result()
  377. self._condition.wait(timeout)
  378. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  379. raise CancelledError()
  380. elif self._state == FINISHED:
  381. return self.__get_result()
  382. else:
  383. raise TimeoutError()
  384. def exception_info(self, timeout=None):
  385. """Return a tuple of (exception, traceback) raised by the call that the
  386. future represents.
  387. Args:
  388. timeout: The number of seconds to wait for the exception if the
  389. future isn't done. If None, then there is no limit on the wait
  390. time.
  391. Returns:
  392. The exception raised by the call that the future represents or None
  393. if the call completed without raising.
  394. Raises:
  395. CancelledError: If the future was cancelled.
  396. TimeoutError: If the future didn't finish executing before the given
  397. timeout.
  398. """
  399. with self._condition:
  400. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  401. raise CancelledError()
  402. elif self._state == FINISHED:
  403. return self._exception, self._traceback
  404. self._condition.wait(timeout)
  405. if self._state in [CANCELLED, CANCELLED_AND_NOTIFIED]:
  406. raise CancelledError()
  407. elif self._state == FINISHED:
  408. return self._exception, self._traceback
  409. else:
  410. raise TimeoutError()
  411. def exception(self, timeout=None):
  412. """Return the exception raised by the call that the future represents.
  413. Args:
  414. timeout: The number of seconds to wait for the exception if the
  415. future isn't done. If None, then there is no limit on the wait
  416. time.
  417. Returns:
  418. The exception raised by the call that the future represents or None
  419. if the call completed without raising.
  420. Raises:
  421. CancelledError: If the future was cancelled.
  422. TimeoutError: If the future didn't finish executing before the given
  423. timeout.
  424. """
  425. return self.exception_info(timeout)[0]
  426. # The following methods should only be used by Executors and in tests.
  427. def set_running_or_notify_cancel(self):
  428. """Mark the future as running or process any cancel notifications.
  429. Should only be used by Executor implementations and unit tests.
  430. If the future has been cancelled (cancel() was called and returned
  431. True) then any threads waiting on the future completing (though calls
  432. to as_completed() or wait()) are notified and False is returned.
  433. If the future was not cancelled then it is put in the running state
  434. (future calls to running() will return True) and True is returned.
  435. This method should be called by Executor implementations before
  436. executing the work associated with this future. If this method returns
  437. False then the work should not be executed.
  438. Returns:
  439. False if the Future was cancelled, True otherwise.
  440. Raises:
  441. RuntimeError: if this method was already called or if set_result()
  442. or set_exception() was called.
  443. """
  444. with self._condition:
  445. if self._state == CANCELLED:
  446. self._state = CANCELLED_AND_NOTIFIED
  447. for waiter in self._waiters:
  448. waiter.add_cancelled(self)
  449. # self._condition.notify_all() is not necessary because
  450. # self.cancel() triggers a notification.
  451. return False
  452. elif self._state == PENDING:
  453. self._state = RUNNING
  454. return True
  455. else:
  456. LOGGER.critical('Future %s in unexpected state: %s',
  457. id(self),
  458. self._state)
  459. raise RuntimeError('Future in unexpected state')
  460. def set_result(self, result):
  461. """Sets the return value of work associated with the future.
  462. Should only be used by Executor implementations and unit tests.
  463. """
  464. with self._condition:
  465. self._result = result
  466. self._state = FINISHED
  467. for waiter in self._waiters:
  468. waiter.add_result(self)
  469. self._condition.notify_all()
  470. self._invoke_callbacks()
  471. def set_exception_info(self, exception, traceback):
  472. """Sets the result of the future as being the given exception
  473. and traceback.
  474. Should only be used by Executor implementations and unit tests.
  475. """
  476. with self._condition:
  477. self._exception = exception
  478. self._traceback = traceback
  479. self._state = FINISHED
  480. for waiter in self._waiters:
  481. waiter.add_exception(self)
  482. self._condition.notify_all()
  483. self._invoke_callbacks()
  484. def set_exception(self, exception):
  485. """Sets the result of the future as being the given exception.
  486. Should only be used by Executor implementations and unit tests.
  487. """
  488. self.set_exception_info(exception, None)
  489. class Executor(object):
  490. """This is an abstract base class for concrete asynchronous executors."""
  491. def submit(self, fn, *args, **kwargs):
  492. """Submits a callable to be executed with the given arguments.
  493. Schedules the callable to be executed as fn(*args, **kwargs) and returns
  494. a Future instance representing the execution of the callable.
  495. Returns:
  496. A Future representing the given call.
  497. """
  498. raise NotImplementedError()
  499. def map(self, fn, *iterables, **kwargs):
  500. """Returns an iterator equivalent to map(fn, iter).
  501. Args:
  502. fn: A callable that will take as many arguments as there are
  503. passed iterables.
  504. timeout: The maximum number of seconds to wait. If None, then there
  505. is no limit on the wait time.
  506. Returns:
  507. An iterator equivalent to: map(func, *iterables) but the calls may
  508. be evaluated out-of-order.
  509. Raises:
  510. TimeoutError: If the entire result iterator could not be generated
  511. before the given timeout.
  512. Exception: If fn(*args) raises for any values.
  513. """
  514. timeout = kwargs.get('timeout')
  515. if timeout is not None:
  516. end_time = timeout + time.time()
  517. fs = [self.submit(fn, *args) for args in itertools.izip(*iterables)]
  518. # Yield must be hidden in closure so that the futures are submitted
  519. # before the first iterator value is required.
  520. def result_iterator():
  521. try:
  522. # reverse to keep finishing order
  523. fs.reverse()
  524. while fs:
  525. # Careful not to keep a reference to the popped future
  526. if timeout is None:
  527. yield fs.pop().result()
  528. else:
  529. yield fs.pop().result(end_time - time.time())
  530. finally:
  531. for future in fs:
  532. future.cancel()
  533. return result_iterator()
  534. def shutdown(self, wait=True):
  535. """Clean-up the resources associated with the Executor.
  536. It is safe to call this method several times. Otherwise, no other
  537. methods can be called after this one.
  538. Args:
  539. wait: If True then shutdown will not return until all running
  540. futures have finished executing and the resources used by the
  541. executor have been reclaimed.
  542. """
  543. pass
  544. def __enter__(self):
  545. return self
  546. def __exit__(self, exc_type, exc_val, exc_tb):
  547. self.shutdown(wait=True)
  548. return False