PageRenderTime 62ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/asyncio/tasks.py

https://bitbucket.org/atsuoishimoto/cpython
Python | 663 lines | 563 code | 36 blank | 64 comment | 18 complexity | d4534c99c0bfc517c28033575b51a1ea MD5 | raw file
Possible License(s): 0BSD
  1. """Support for tasks, coroutines and the scheduler."""
  2. __all__ = ['coroutine', 'Task',
  3. 'iscoroutinefunction', 'iscoroutine',
  4. 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
  5. 'wait', 'wait_for', 'as_completed', 'sleep', 'async',
  6. 'gather', 'shield',
  7. ]
  8. import collections
  9. import concurrent.futures
  10. import functools
  11. import inspect
  12. import linecache
  13. import traceback
  14. import weakref
  15. from . import events
  16. from . import futures
  17. from .log import logger
  18. # If you set _DEBUG to true, @coroutine will wrap the resulting
  19. # generator objects in a CoroWrapper instance (defined below). That
  20. # instance will log a message when the generator is never iterated
  21. # over, which may happen when you forget to use "yield from" with a
  22. # coroutine call. Note that the value of the _DEBUG flag is taken
  23. # when the decorator is used, so to be of any use it must be set
  24. # before you define your coroutines. A downside of using this feature
  25. # is that tracebacks show entries for the CoroWrapper.__next__ method
  26. # when _DEBUG is true.
  27. _DEBUG = False
  28. class CoroWrapper:
  29. # Wrapper for coroutine in _DEBUG mode.
  30. __slots__ = ['gen', 'func', '__name__', '__doc__']
  31. def __init__(self, gen, func):
  32. assert inspect.isgenerator(gen), gen
  33. self.gen = gen
  34. self.func = func
  35. def __iter__(self):
  36. return self
  37. def __next__(self):
  38. return next(self.gen)
  39. def send(self, value):
  40. return self.gen.send(value)
  41. def throw(self, exc):
  42. return self.gen.throw(exc)
  43. def close(self):
  44. return self.gen.close()
  45. def __del__(self):
  46. frame = self.gen.gi_frame
  47. if frame is not None and frame.f_lasti == -1:
  48. func = self.func
  49. code = func.__code__
  50. filename = code.co_filename
  51. lineno = code.co_firstlineno
  52. logger.error(
  53. 'Coroutine %r defined at %s:%s was never yielded from',
  54. func.__name__, filename, lineno)
  55. def coroutine(func):
  56. """Decorator to mark coroutines.
  57. If the coroutine is not yielded from before it is destroyed,
  58. an error message is logged.
  59. """
  60. if inspect.isgeneratorfunction(func):
  61. coro = func
  62. else:
  63. @functools.wraps(func)
  64. def coro(*args, **kw):
  65. res = func(*args, **kw)
  66. if isinstance(res, futures.Future) or inspect.isgenerator(res):
  67. res = yield from res
  68. return res
  69. if not _DEBUG:
  70. wrapper = coro
  71. else:
  72. @functools.wraps(func)
  73. def wrapper(*args, **kwds):
  74. w = CoroWrapper(coro(*args, **kwds), func)
  75. w.__name__ = coro.__name__
  76. w.__doc__ = coro.__doc__
  77. return w
  78. wrapper._is_coroutine = True # For iscoroutinefunction().
  79. return wrapper
  80. def iscoroutinefunction(func):
  81. """Return True if func is a decorated coroutine function."""
  82. return getattr(func, '_is_coroutine', False)
  83. def iscoroutine(obj):
  84. """Return True if obj is a coroutine object."""
  85. return isinstance(obj, CoroWrapper) or inspect.isgenerator(obj)
  86. class Task(futures.Future):
  87. """A coroutine wrapped in a Future."""
  88. # An important invariant maintained while a Task not done:
  89. #
  90. # - Either _fut_waiter is None, and _step() is scheduled;
  91. # - or _fut_waiter is some Future, and _step() is *not* scheduled.
  92. #
  93. # The only transition from the latter to the former is through
  94. # _wakeup(). When _fut_waiter is not None, one of its callbacks
  95. # must be _wakeup().
  96. # Weak set containing all tasks alive.
  97. _all_tasks = weakref.WeakSet()
  98. # Dictionary containing tasks that are currently active in
  99. # all running event loops. {EventLoop: Task}
  100. _current_tasks = {}
  101. @classmethod
  102. def current_task(cls, loop=None):
  103. """Return the currently running task in an event loop or None.
  104. By default the current task for the current event loop is returned.
  105. None is returned when called not in the context of a Task.
  106. """
  107. if loop is None:
  108. loop = events.get_event_loop()
  109. return cls._current_tasks.get(loop)
  110. @classmethod
  111. def all_tasks(cls, loop=None):
  112. """Return a set of all tasks for an event loop.
  113. By default all tasks for the current event loop are returned.
  114. """
  115. if loop is None:
  116. loop = events.get_event_loop()
  117. return {t for t in cls._all_tasks if t._loop is loop}
  118. def __init__(self, coro, *, loop=None):
  119. assert iscoroutine(coro), repr(coro) # Not a coroutine function!
  120. super().__init__(loop=loop)
  121. self._coro = iter(coro) # Use the iterator just in case.
  122. self._fut_waiter = None
  123. self._must_cancel = False
  124. self._loop.call_soon(self._step)
  125. self.__class__._all_tasks.add(self)
  126. def __repr__(self):
  127. res = super().__repr__()
  128. if (self._must_cancel and
  129. self._state == futures._PENDING and
  130. '<PENDING' in res):
  131. res = res.replace('<PENDING', '<CANCELLING', 1)
  132. i = res.find('<')
  133. if i < 0:
  134. i = len(res)
  135. res = res[:i] + '(<{}>)'.format(self._coro.__name__) + res[i:]
  136. return res
  137. def get_stack(self, *, limit=None):
  138. """Return the list of stack frames for this task's coroutine.
  139. If the coroutine is active, this returns the stack where it is
  140. suspended. If the coroutine has completed successfully or was
  141. cancelled, this returns an empty list. If the coroutine was
  142. terminated by an exception, this returns the list of traceback
  143. frames.
  144. The frames are always ordered from oldest to newest.
  145. The optional limit gives the maximum nummber of frames to
  146. return; by default all available frames are returned. Its
  147. meaning differs depending on whether a stack or a traceback is
  148. returned: the newest frames of a stack are returned, but the
  149. oldest frames of a traceback are returned. (This matches the
  150. behavior of the traceback module.)
  151. For reasons beyond our control, only one stack frame is
  152. returned for a suspended coroutine.
  153. """
  154. frames = []
  155. f = self._coro.gi_frame
  156. if f is not None:
  157. while f is not None:
  158. if limit is not None:
  159. if limit <= 0:
  160. break
  161. limit -= 1
  162. frames.append(f)
  163. f = f.f_back
  164. frames.reverse()
  165. elif self._exception is not None:
  166. tb = self._exception.__traceback__
  167. while tb is not None:
  168. if limit is not None:
  169. if limit <= 0:
  170. break
  171. limit -= 1
  172. frames.append(tb.tb_frame)
  173. tb = tb.tb_next
  174. return frames
  175. def print_stack(self, *, limit=None, file=None):
  176. """Print the stack or traceback for this task's coroutine.
  177. This produces output similar to that of the traceback module,
  178. for the frames retrieved by get_stack(). The limit argument
  179. is passed to get_stack(). The file argument is an I/O stream
  180. to which the output goes; by default it goes to sys.stderr.
  181. """
  182. extracted_list = []
  183. checked = set()
  184. for f in self.get_stack(limit=limit):
  185. lineno = f.f_lineno
  186. co = f.f_code
  187. filename = co.co_filename
  188. name = co.co_name
  189. if filename not in checked:
  190. checked.add(filename)
  191. linecache.checkcache(filename)
  192. line = linecache.getline(filename, lineno, f.f_globals)
  193. extracted_list.append((filename, lineno, name, line))
  194. exc = self._exception
  195. if not extracted_list:
  196. print('No stack for %r' % self, file=file)
  197. elif exc is not None:
  198. print('Traceback for %r (most recent call last):' % self,
  199. file=file)
  200. else:
  201. print('Stack for %r (most recent call last):' % self,
  202. file=file)
  203. traceback.print_list(extracted_list, file=file)
  204. if exc is not None:
  205. for line in traceback.format_exception_only(exc.__class__, exc):
  206. print(line, file=file, end='')
  207. def cancel(self):
  208. if self.done():
  209. return False
  210. if self._fut_waiter is not None:
  211. if self._fut_waiter.cancel():
  212. # Leave self._fut_waiter; it may be a Task that
  213. # catches and ignores the cancellation so we may have
  214. # to cancel it again later.
  215. return True
  216. # It must be the case that self._step is already scheduled.
  217. self._must_cancel = True
  218. return True
  219. def _step(self, value=None, exc=None):
  220. assert not self.done(), \
  221. '_step(): already done: {!r}, {!r}, {!r}'.format(self, value, exc)
  222. if self._must_cancel:
  223. if not isinstance(exc, futures.CancelledError):
  224. exc = futures.CancelledError()
  225. self._must_cancel = False
  226. coro = self._coro
  227. self._fut_waiter = None
  228. self.__class__._current_tasks[self._loop] = self
  229. # Call either coro.throw(exc) or coro.send(value).
  230. try:
  231. if exc is not None:
  232. result = coro.throw(exc)
  233. elif value is not None:
  234. result = coro.send(value)
  235. else:
  236. result = next(coro)
  237. except StopIteration as exc:
  238. self.set_result(exc.value)
  239. except futures.CancelledError as exc:
  240. super().cancel() # I.e., Future.cancel(self).
  241. except Exception as exc:
  242. self.set_exception(exc)
  243. except BaseException as exc:
  244. self.set_exception(exc)
  245. raise
  246. else:
  247. if isinstance(result, futures.Future):
  248. # Yielded Future must come from Future.__iter__().
  249. if result._blocking:
  250. result._blocking = False
  251. result.add_done_callback(self._wakeup)
  252. self._fut_waiter = result
  253. if self._must_cancel:
  254. if self._fut_waiter.cancel():
  255. self._must_cancel = False
  256. else:
  257. self._loop.call_soon(
  258. self._step, None,
  259. RuntimeError(
  260. 'yield was used instead of yield from '
  261. 'in task {!r} with {!r}'.format(self, result)))
  262. elif result is None:
  263. # Bare yield relinquishes control for one event loop iteration.
  264. self._loop.call_soon(self._step)
  265. elif inspect.isgenerator(result):
  266. # Yielding a generator is just wrong.
  267. self._loop.call_soon(
  268. self._step, None,
  269. RuntimeError(
  270. 'yield was used instead of yield from for '
  271. 'generator in task {!r} with {}'.format(
  272. self, result)))
  273. else:
  274. # Yielding something else is an error.
  275. self._loop.call_soon(
  276. self._step, None,
  277. RuntimeError(
  278. 'Task got bad yield: {!r}'.format(result)))
  279. finally:
  280. self.__class__._current_tasks.pop(self._loop)
  281. self = None
  282. def _wakeup(self, future):
  283. try:
  284. value = future.result()
  285. except Exception as exc:
  286. # This may also be a cancellation.
  287. self._step(None, exc)
  288. else:
  289. self._step(value, None)
  290. self = None # Needed to break cycles when an exception occurs.
  291. # wait() and as_completed() similar to those in PEP 3148.
  292. FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
  293. FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
  294. ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
  295. @coroutine
  296. def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
  297. """Wait for the Futures and coroutines given by fs to complete.
  298. Coroutines will be wrapped in Tasks.
  299. Returns two sets of Future: (done, pending).
  300. Usage:
  301. done, pending = yield from asyncio.wait(fs)
  302. Note: This does not raise TimeoutError! Futures that aren't done
  303. when the timeout occurs are returned in the second set.
  304. """
  305. if not fs:
  306. raise ValueError('Set of coroutines/Futures is empty.')
  307. if loop is None:
  308. loop = events.get_event_loop()
  309. fs = set(async(f, loop=loop) for f in fs)
  310. if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
  311. raise ValueError('Invalid return_when value: {}'.format(return_when))
  312. return (yield from _wait(fs, timeout, return_when, loop))
  313. def _release_waiter(waiter, value=True, *args):
  314. if not waiter.done():
  315. waiter.set_result(value)
  316. @coroutine
  317. def wait_for(fut, timeout, *, loop=None):
  318. """Wait for the single Future or coroutine to complete, with timeout.
  319. Coroutine will be wrapped in Task.
  320. Returns result of the Future or coroutine. When a timeout occurs,
  321. it cancels the task and raises TimeoutError. To avoid the task
  322. cancellation, wrap it in shield().
  323. Usage:
  324. result = yield from asyncio.wait_for(fut, 10.0)
  325. """
  326. if loop is None:
  327. loop = events.get_event_loop()
  328. if timeout is None:
  329. return (yield from fut)
  330. waiter = futures.Future(loop=loop)
  331. timeout_handle = loop.call_later(timeout, _release_waiter, waiter, False)
  332. cb = functools.partial(_release_waiter, waiter, True)
  333. fut = async(fut, loop=loop)
  334. fut.add_done_callback(cb)
  335. try:
  336. if (yield from waiter):
  337. return fut.result()
  338. else:
  339. fut.remove_done_callback(cb)
  340. fut.cancel()
  341. raise futures.TimeoutError()
  342. finally:
  343. timeout_handle.cancel()
  344. @coroutine
  345. def _wait(fs, timeout, return_when, loop):
  346. """Internal helper for wait() and _wait_for().
  347. The fs argument must be a collection of Futures.
  348. """
  349. assert fs, 'Set of Futures is empty.'
  350. waiter = futures.Future(loop=loop)
  351. timeout_handle = None
  352. if timeout is not None:
  353. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  354. counter = len(fs)
  355. def _on_completion(f):
  356. nonlocal counter
  357. counter -= 1
  358. if (counter <= 0 or
  359. return_when == FIRST_COMPLETED or
  360. return_when == FIRST_EXCEPTION and (not f.cancelled() and
  361. f.exception() is not None)):
  362. if timeout_handle is not None:
  363. timeout_handle.cancel()
  364. if not waiter.done():
  365. waiter.set_result(False)
  366. for f in fs:
  367. f.add_done_callback(_on_completion)
  368. try:
  369. yield from waiter
  370. finally:
  371. if timeout_handle is not None:
  372. timeout_handle.cancel()
  373. done, pending = set(), set()
  374. for f in fs:
  375. f.remove_done_callback(_on_completion)
  376. if f.done():
  377. done.add(f)
  378. else:
  379. pending.add(f)
  380. return done, pending
  381. # This is *not* a @coroutine! It is just an iterator (yielding Futures).
  382. def as_completed(fs, *, loop=None, timeout=None):
  383. """Return an iterator whose values, when waited for, are Futures.
  384. This differs from PEP 3148; the proper way to use this is:
  385. for f in as_completed(fs):
  386. result = yield from f # The 'yield from' may raise.
  387. # Use result.
  388. Raises TimeoutError if the timeout occurs before all Futures are
  389. done.
  390. Note: The futures 'f' are not necessarily members of fs.
  391. """
  392. loop = loop if loop is not None else events.get_event_loop()
  393. deadline = None if timeout is None else loop.time() + timeout
  394. todo = set(async(f, loop=loop) for f in fs)
  395. completed = collections.deque()
  396. @coroutine
  397. def _wait_for_one():
  398. while not completed:
  399. timeout = None
  400. if deadline is not None:
  401. timeout = deadline - loop.time()
  402. if timeout < 0:
  403. raise futures.TimeoutError()
  404. done, pending = yield from _wait(
  405. todo, timeout, FIRST_COMPLETED, loop)
  406. # Multiple callers might be waiting for the same events
  407. # and getting the same outcome. Dedupe by updating todo.
  408. for f in done:
  409. if f in todo:
  410. todo.remove(f)
  411. completed.append(f)
  412. f = completed.popleft()
  413. return f.result() # May raise.
  414. for _ in range(len(todo)):
  415. yield _wait_for_one()
  416. @coroutine
  417. def sleep(delay, result=None, *, loop=None):
  418. """Coroutine that completes after a given time (in seconds)."""
  419. future = futures.Future(loop=loop)
  420. h = future._loop.call_later(delay, future.set_result, result)
  421. try:
  422. return (yield from future)
  423. finally:
  424. h.cancel()
  425. def async(coro_or_future, *, loop=None):
  426. """Wrap a coroutine in a future.
  427. If the argument is a Future, it is returned directly.
  428. """
  429. if isinstance(coro_or_future, futures.Future):
  430. if loop is not None and loop is not coro_or_future._loop:
  431. raise ValueError('loop argument must agree with Future')
  432. return coro_or_future
  433. elif iscoroutine(coro_or_future):
  434. return Task(coro_or_future, loop=loop)
  435. else:
  436. raise TypeError('A Future or coroutine is required')
  437. class _GatheringFuture(futures.Future):
  438. """Helper for gather().
  439. This overrides cancel() to cancel all the children and act more
  440. like Task.cancel(), which doesn't immediately mark itself as
  441. cancelled.
  442. """
  443. def __init__(self, children, *, loop=None):
  444. super().__init__(loop=loop)
  445. self._children = children
  446. def cancel(self):
  447. if self.done():
  448. return False
  449. for child in self._children:
  450. child.cancel()
  451. return True
  452. def gather(*coros_or_futures, loop=None, return_exceptions=False):
  453. """Return a future aggregating results from the given coroutines
  454. or futures.
  455. All futures must share the same event loop. If all the tasks are
  456. done successfully, the returned future's result is the list of
  457. results (in the order of the original sequence, not necessarily
  458. the order of results arrival). If *result_exception* is True,
  459. exceptions in the tasks are treated the same as successful
  460. results, and gathered in the result list; otherwise, the first
  461. raised exception will be immediately propagated to the returned
  462. future.
  463. Cancellation: if the outer Future is cancelled, all children (that
  464. have not completed yet) are also cancelled. If any child is
  465. cancelled, this is treated as if it raised CancelledError --
  466. the outer Future is *not* cancelled in this case. (This is to
  467. prevent the cancellation of one child to cause other children to
  468. be cancelled.)
  469. """
  470. children = [async(fut, loop=loop) for fut in coros_or_futures]
  471. n = len(children)
  472. if n == 0:
  473. outer = futures.Future(loop=loop)
  474. outer.set_result([])
  475. return outer
  476. if loop is None:
  477. loop = children[0]._loop
  478. for fut in children:
  479. if fut._loop is not loop:
  480. raise ValueError("futures are tied to different event loops")
  481. outer = _GatheringFuture(children, loop=loop)
  482. nfinished = 0
  483. results = [None] * n
  484. def _done_callback(i, fut):
  485. nonlocal nfinished
  486. if outer._state != futures._PENDING:
  487. if fut._exception is not None:
  488. # Mark exception retrieved.
  489. fut.exception()
  490. return
  491. if fut._state == futures._CANCELLED:
  492. res = futures.CancelledError()
  493. if not return_exceptions:
  494. outer.set_exception(res)
  495. return
  496. elif fut._exception is not None:
  497. res = fut.exception() # Mark exception retrieved.
  498. if not return_exceptions:
  499. outer.set_exception(res)
  500. return
  501. else:
  502. res = fut._result
  503. results[i] = res
  504. nfinished += 1
  505. if nfinished == n:
  506. outer.set_result(results)
  507. for i, fut in enumerate(children):
  508. fut.add_done_callback(functools.partial(_done_callback, i))
  509. return outer
  510. def shield(arg, *, loop=None):
  511. """Wait for a future, shielding it from cancellation.
  512. The statement
  513. res = yield from shield(something())
  514. is exactly equivalent to the statement
  515. res = yield from something()
  516. *except* that if the coroutine containing it is cancelled, the
  517. task running in something() is not cancelled. From the POV of
  518. something(), the cancellation did not happen. But its caller is
  519. still cancelled, so the yield-from expression still raises
  520. CancelledError. Note: If something() is cancelled by other means
  521. this will still cancel shield().
  522. If you want to completely ignore cancellation (not recommended)
  523. you can combine shield() with a try/except clause, as follows:
  524. try:
  525. res = yield from shield(something())
  526. except CancelledError:
  527. res = None
  528. """
  529. inner = async(arg, loop=loop)
  530. if inner.done():
  531. # Shortcut.
  532. return inner
  533. loop = inner._loop
  534. outer = futures.Future(loop=loop)
  535. def _done_callback(inner):
  536. if outer.cancelled():
  537. # Mark inner's result as retrieved.
  538. inner.cancelled() or inner.exception()
  539. return
  540. if inner.cancelled():
  541. outer.cancel()
  542. else:
  543. exc = inner.exception()
  544. if exc is not None:
  545. outer.set_exception(exc)
  546. else:
  547. outer.set_result(inner.result())
  548. inner.add_done_callback(_done_callback)
  549. return outer