PageRenderTime 28ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/asyncio/tasks.py

https://github.com/albertz/CPython
Python | 900 lines | 828 code | 28 blank | 44 comment | 29 complexity | 42acafea52474410044b923dd3cb27b2 MD5 | raw file
  1. """Support for tasks, coroutines and the scheduler."""
  2. __all__ = (
  3. 'Task', 'create_task',
  4. 'FIRST_COMPLETED', 'FIRST_EXCEPTION', 'ALL_COMPLETED',
  5. 'wait', 'wait_for', 'as_completed', 'sleep',
  6. 'gather', 'shield', 'ensure_future', 'run_coroutine_threadsafe',
  7. 'current_task', 'all_tasks',
  8. '_register_task', '_unregister_task', '_enter_task', '_leave_task',
  9. )
  10. import concurrent.futures
  11. import contextvars
  12. import functools
  13. import inspect
  14. import types
  15. import warnings
  16. import weakref
  17. from . import base_tasks
  18. from . import coroutines
  19. from . import events
  20. from . import futures
  21. from .coroutines import coroutine
  22. def current_task(loop=None):
  23. """Return a currently executed task."""
  24. if loop is None:
  25. loop = events.get_running_loop()
  26. return _current_tasks.get(loop)
  27. def all_tasks(loop=None):
  28. """Return a set of all tasks for the loop."""
  29. if loop is None:
  30. loop = events.get_running_loop()
  31. # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
  32. # thread while we do so. Therefore we cast it to list prior to filtering. The list
  33. # cast itself requires iteration, so we repeat it several times ignoring
  34. # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
  35. # details.
  36. i = 0
  37. while True:
  38. try:
  39. tasks = list(_all_tasks)
  40. except RuntimeError:
  41. i += 1
  42. if i >= 1000:
  43. raise
  44. else:
  45. break
  46. return {t for t in tasks
  47. if futures._get_loop(t) is loop and not t.done()}
  48. def _all_tasks_compat(loop=None):
  49. # Different from "all_task()" by returning *all* Tasks, including
  50. # the completed ones. Used to implement deprecated "Tasks.all_task()"
  51. # method.
  52. if loop is None:
  53. loop = events.get_event_loop()
  54. # Looping over a WeakSet (_all_tasks) isn't safe as it can be updated from another
  55. # thread while we do so. Therefore we cast it to list prior to filtering. The list
  56. # cast itself requires iteration, so we repeat it several times ignoring
  57. # RuntimeErrors (which are not very likely to occur). See issues 34970 and 36607 for
  58. # details.
  59. i = 0
  60. while True:
  61. try:
  62. tasks = list(_all_tasks)
  63. except RuntimeError:
  64. i += 1
  65. if i >= 1000:
  66. raise
  67. else:
  68. break
  69. return {t for t in tasks if futures._get_loop(t) is loop}
  70. class Task(futures._PyFuture): # Inherit Python Task implementation
  71. # from a Python Future implementation.
  72. """A coroutine wrapped in a Future."""
  73. # An important invariant maintained while a Task not done:
  74. #
  75. # - Either _fut_waiter is None, and _step() is scheduled;
  76. # - or _fut_waiter is some Future, and _step() is *not* scheduled.
  77. #
  78. # The only transition from the latter to the former is through
  79. # _wakeup(). When _fut_waiter is not None, one of its callbacks
  80. # must be _wakeup().
  81. # If False, don't log a message if the task is destroyed whereas its
  82. # status is still pending
  83. _log_destroy_pending = True
  84. @classmethod
  85. def current_task(cls, loop=None):
  86. """Return the currently running task in an event loop or None.
  87. By default the current task for the current event loop is returned.
  88. None is returned when called not in the context of a Task.
  89. """
  90. warnings.warn("Task.current_task() is deprecated, "
  91. "use asyncio.current_task() instead",
  92. PendingDeprecationWarning,
  93. stacklevel=2)
  94. if loop is None:
  95. loop = events.get_event_loop()
  96. return current_task(loop)
  97. @classmethod
  98. def all_tasks(cls, loop=None):
  99. """Return a set of all tasks for an event loop.
  100. By default all tasks for the current event loop are returned.
  101. """
  102. warnings.warn("Task.all_tasks() is deprecated, "
  103. "use asyncio.all_tasks() instead",
  104. PendingDeprecationWarning,
  105. stacklevel=2)
  106. return _all_tasks_compat(loop)
  107. def __init__(self, coro, *, loop=None):
  108. super().__init__(loop=loop)
  109. if self._source_traceback:
  110. del self._source_traceback[-1]
  111. if not coroutines.iscoroutine(coro):
  112. # raise after Future.__init__(), attrs are required for __del__
  113. # prevent logging for pending task in __del__
  114. self._log_destroy_pending = False
  115. raise TypeError(f"a coroutine was expected, got {coro!r}")
  116. self._must_cancel = False
  117. self._fut_waiter = None
  118. self._coro = coro
  119. self._context = contextvars.copy_context()
  120. self._loop.call_soon(self.__step, context=self._context)
  121. _register_task(self)
  122. def __del__(self):
  123. if self._state == futures._PENDING and self._log_destroy_pending:
  124. context = {
  125. 'task': self,
  126. 'message': 'Task was destroyed but it is pending!',
  127. }
  128. if self._source_traceback:
  129. context['source_traceback'] = self._source_traceback
  130. self._loop.call_exception_handler(context)
  131. super().__del__()
  132. def _repr_info(self):
  133. return base_tasks._task_repr_info(self)
  134. def set_result(self, result):
  135. raise RuntimeError('Task does not support set_result operation')
  136. def set_exception(self, exception):
  137. raise RuntimeError('Task does not support set_exception operation')
  138. def get_stack(self, *, limit=None):
  139. """Return the list of stack frames for this task's coroutine.
  140. If the coroutine is not done, this returns the stack where it is
  141. suspended. If the coroutine has completed successfully or was
  142. cancelled, this returns an empty list. If the coroutine was
  143. terminated by an exception, this returns the list of traceback
  144. frames.
  145. The frames are always ordered from oldest to newest.
  146. The optional limit gives the maximum number of frames to
  147. return; by default all available frames are returned. Its
  148. meaning differs depending on whether a stack or a traceback is
  149. returned: the newest frames of a stack are returned, but the
  150. oldest frames of a traceback are returned. (This matches the
  151. behavior of the traceback module.)
  152. For reasons beyond our control, only one stack frame is
  153. returned for a suspended coroutine.
  154. """
  155. return base_tasks._task_get_stack(self, limit)
  156. def print_stack(self, *, limit=None, file=None):
  157. """Print the stack or traceback for this task's coroutine.
  158. This produces output similar to that of the traceback module,
  159. for the frames retrieved by get_stack(). The limit argument
  160. is passed to get_stack(). The file argument is an I/O stream
  161. to which the output is written; by default output is written
  162. to sys.stderr.
  163. """
  164. return base_tasks._task_print_stack(self, limit, file)
  165. def cancel(self):
  166. """Request that this task cancel itself.
  167. This arranges for a CancelledError to be thrown into the
  168. wrapped coroutine on the next cycle through the event loop.
  169. The coroutine then has a chance to clean up or even deny
  170. the request using try/except/finally.
  171. Unlike Future.cancel, this does not guarantee that the
  172. task will be cancelled: the exception might be caught and
  173. acted upon, delaying cancellation of the task or preventing
  174. cancellation completely. The task may also return a value or
  175. raise a different exception.
  176. Immediately after this method is called, Task.cancelled() will
  177. not return True (unless the task was already cancelled). A
  178. task will be marked as cancelled when the wrapped coroutine
  179. terminates with a CancelledError exception (even if cancel()
  180. was not called).
  181. """
  182. self._log_traceback = False
  183. if self.done():
  184. return False
  185. if self._fut_waiter is not None:
  186. if self._fut_waiter.cancel():
  187. # Leave self._fut_waiter; it may be a Task that
  188. # catches and ignores the cancellation so we may have
  189. # to cancel it again later.
  190. return True
  191. # It must be the case that self.__step is already scheduled.
  192. self._must_cancel = True
  193. return True
  194. def __step(self, exc=None):
  195. if self.done():
  196. raise futures.InvalidStateError(
  197. f'_step(): already done: {self!r}, {exc!r}')
  198. if self._must_cancel:
  199. if not isinstance(exc, futures.CancelledError):
  200. exc = futures.CancelledError()
  201. self._must_cancel = False
  202. coro = self._coro
  203. self._fut_waiter = None
  204. _enter_task(self._loop, self)
  205. # Call either coro.throw(exc) or coro.send(None).
  206. try:
  207. if exc is None:
  208. # We use the `send` method directly, because coroutines
  209. # don't have `__iter__` and `__next__` methods.
  210. result = coro.send(None)
  211. else:
  212. result = coro.throw(exc)
  213. except StopIteration as exc:
  214. if self._must_cancel:
  215. # Task is cancelled right before coro stops.
  216. self._must_cancel = False
  217. super().set_exception(futures.CancelledError())
  218. else:
  219. super().set_result(exc.value)
  220. except futures.CancelledError:
  221. super().cancel() # I.e., Future.cancel(self).
  222. except Exception as exc:
  223. super().set_exception(exc)
  224. except BaseException as exc:
  225. super().set_exception(exc)
  226. raise
  227. else:
  228. blocking = getattr(result, '_asyncio_future_blocking', None)
  229. if blocking is not None:
  230. # Yielded Future must come from Future.__iter__().
  231. if futures._get_loop(result) is not self._loop:
  232. new_exc = RuntimeError(
  233. f'Task {self!r} got Future '
  234. f'{result!r} attached to a different loop')
  235. self._loop.call_soon(
  236. self.__step, new_exc, context=self._context)
  237. elif blocking:
  238. if result is self:
  239. new_exc = RuntimeError(
  240. f'Task cannot await on itself: {self!r}')
  241. self._loop.call_soon(
  242. self.__step, new_exc, context=self._context)
  243. else:
  244. result._asyncio_future_blocking = False
  245. result.add_done_callback(
  246. self.__wakeup, context=self._context)
  247. self._fut_waiter = result
  248. if self._must_cancel:
  249. if self._fut_waiter.cancel():
  250. self._must_cancel = False
  251. else:
  252. new_exc = RuntimeError(
  253. f'yield was used instead of yield from '
  254. f'in task {self!r} with {result!r}')
  255. self._loop.call_soon(
  256. self.__step, new_exc, context=self._context)
  257. elif result is None:
  258. # Bare yield relinquishes control for one event loop iteration.
  259. self._loop.call_soon(self.__step, context=self._context)
  260. elif inspect.isgenerator(result):
  261. # Yielding a generator is just wrong.
  262. new_exc = RuntimeError(
  263. f'yield was used instead of yield from for '
  264. f'generator in task {self!r} with {result!r}')
  265. self._loop.call_soon(
  266. self.__step, new_exc, context=self._context)
  267. else:
  268. # Yielding something else is an error.
  269. new_exc = RuntimeError(f'Task got bad yield: {result!r}')
  270. self._loop.call_soon(
  271. self.__step, new_exc, context=self._context)
  272. finally:
  273. _leave_task(self._loop, self)
  274. self = None # Needed to break cycles when an exception occurs.
  275. def __wakeup(self, future):
  276. try:
  277. future.result()
  278. except Exception as exc:
  279. # This may also be a cancellation.
  280. self.__step(exc)
  281. else:
  282. # Don't pass the value of `future.result()` explicitly,
  283. # as `Future.__iter__` and `Future.__await__` don't need it.
  284. # If we call `_step(value, None)` instead of `_step()`,
  285. # Python eval loop would use `.send(value)` method call,
  286. # instead of `__next__()`, which is slower for futures
  287. # that return non-generator iterators from their `__iter__`.
  288. self.__step()
  289. self = None # Needed to break cycles when an exception occurs.
  290. _PyTask = Task
  291. try:
  292. import _asyncio
  293. except ImportError:
  294. pass
  295. else:
  296. # _CTask is needed for tests.
  297. Task = _CTask = _asyncio.Task
  298. def create_task(coro):
  299. """Schedule the execution of a coroutine object in a spawn task.
  300. Return a Task object.
  301. """
  302. loop = events.get_running_loop()
  303. return loop.create_task(coro)
  304. # wait() and as_completed() similar to those in PEP 3148.
  305. FIRST_COMPLETED = concurrent.futures.FIRST_COMPLETED
  306. FIRST_EXCEPTION = concurrent.futures.FIRST_EXCEPTION
  307. ALL_COMPLETED = concurrent.futures.ALL_COMPLETED
  308. async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED):
  309. """Wait for the Futures and coroutines given by fs to complete.
  310. The sequence futures must not be empty.
  311. Coroutines will be wrapped in Tasks.
  312. Returns two sets of Future: (done, pending).
  313. Usage:
  314. done, pending = await asyncio.wait(fs)
  315. Note: This does not raise TimeoutError! Futures that aren't done
  316. when the timeout occurs are returned in the second set.
  317. """
  318. if futures.isfuture(fs) or coroutines.iscoroutine(fs):
  319. raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
  320. if not fs:
  321. raise ValueError('Set of coroutines/Futures is empty.')
  322. if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED):
  323. raise ValueError(f'Invalid return_when value: {return_when}')
  324. if loop is None:
  325. loop = events.get_event_loop()
  326. fs = {ensure_future(f, loop=loop) for f in set(fs)}
  327. return await _wait(fs, timeout, return_when, loop)
  328. def _release_waiter(waiter, *args):
  329. if not waiter.done():
  330. waiter.set_result(None)
  331. async def wait_for(fut, timeout, *, loop=None):
  332. """Wait for the single Future or coroutine to complete, with timeout.
  333. Coroutine will be wrapped in Task.
  334. Returns result of the Future or coroutine. When a timeout occurs,
  335. it cancels the task and raises TimeoutError. To avoid the task
  336. cancellation, wrap it in shield().
  337. If the wait is cancelled, the task is also cancelled.
  338. This function is a coroutine.
  339. """
  340. if loop is None:
  341. loop = events.get_event_loop()
  342. if timeout is None:
  343. return await fut
  344. if timeout <= 0:
  345. fut = ensure_future(fut, loop=loop)
  346. if fut.done():
  347. return fut.result()
  348. fut.cancel()
  349. raise futures.TimeoutError()
  350. waiter = loop.create_future()
  351. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  352. cb = functools.partial(_release_waiter, waiter)
  353. fut = ensure_future(fut, loop=loop)
  354. fut.add_done_callback(cb)
  355. try:
  356. # wait until the future completes or the timeout
  357. try:
  358. await waiter
  359. except futures.CancelledError:
  360. fut.remove_done_callback(cb)
  361. fut.cancel()
  362. raise
  363. if fut.done():
  364. return fut.result()
  365. else:
  366. fut.remove_done_callback(cb)
  367. # We must ensure that the task is not running
  368. # after wait_for() returns.
  369. # See https://bugs.python.org/issue32751
  370. await _cancel_and_wait(fut, loop=loop)
  371. raise futures.TimeoutError()
  372. finally:
  373. timeout_handle.cancel()
  374. async def _wait(fs, timeout, return_when, loop):
  375. """Internal helper for wait().
  376. The fs argument must be a collection of Futures.
  377. """
  378. assert fs, 'Set of Futures is empty.'
  379. waiter = loop.create_future()
  380. timeout_handle = None
  381. if timeout is not None:
  382. timeout_handle = loop.call_later(timeout, _release_waiter, waiter)
  383. counter = len(fs)
  384. def _on_completion(f):
  385. nonlocal counter
  386. counter -= 1
  387. if (counter <= 0 or
  388. return_when == FIRST_COMPLETED or
  389. return_when == FIRST_EXCEPTION and (not f.cancelled() and
  390. f.exception() is not None)):
  391. if timeout_handle is not None:
  392. timeout_handle.cancel()
  393. if not waiter.done():
  394. waiter.set_result(None)
  395. for f in fs:
  396. f.add_done_callback(_on_completion)
  397. try:
  398. await waiter
  399. finally:
  400. if timeout_handle is not None:
  401. timeout_handle.cancel()
  402. for f in fs:
  403. f.remove_done_callback(_on_completion)
  404. done, pending = set(), set()
  405. for f in fs:
  406. if f.done():
  407. done.add(f)
  408. else:
  409. pending.add(f)
  410. return done, pending
  411. async def _cancel_and_wait(fut, loop):
  412. """Cancel the *fut* future or task and wait until it completes."""
  413. waiter = loop.create_future()
  414. cb = functools.partial(_release_waiter, waiter)
  415. fut.add_done_callback(cb)
  416. try:
  417. fut.cancel()
  418. # We cannot wait on *fut* directly to make
  419. # sure _cancel_and_wait itself is reliably cancellable.
  420. await waiter
  421. finally:
  422. fut.remove_done_callback(cb)
  423. # This is *not* a @coroutine! It is just an iterator (yielding Futures).
  424. def as_completed(fs, *, loop=None, timeout=None):
  425. """Return an iterator whose values are coroutines.
  426. When waiting for the yielded coroutines you'll get the results (or
  427. exceptions!) of the original Futures (or coroutines), in the order
  428. in which and as soon as they complete.
  429. This differs from PEP 3148; the proper way to use this is:
  430. for f in as_completed(fs):
  431. result = await f # The 'await' may raise.
  432. # Use result.
  433. If a timeout is specified, the 'await' will raise
  434. TimeoutError when the timeout occurs before all Futures are done.
  435. Note: The futures 'f' are not necessarily members of fs.
  436. """
  437. if futures.isfuture(fs) or coroutines.iscoroutine(fs):
  438. raise TypeError(f"expect a list of futures, not {type(fs).__name__}")
  439. loop = loop if loop is not None else events.get_event_loop()
  440. todo = {ensure_future(f, loop=loop) for f in set(fs)}
  441. from .queues import Queue # Import here to avoid circular import problem.
  442. done = Queue(loop=loop)
  443. timeout_handle = None
  444. def _on_timeout():
  445. for f in todo:
  446. f.remove_done_callback(_on_completion)
  447. done.put_nowait(None) # Queue a dummy value for _wait_for_one().
  448. todo.clear() # Can't do todo.remove(f) in the loop.
  449. def _on_completion(f):
  450. if not todo:
  451. return # _on_timeout() was here first.
  452. todo.remove(f)
  453. done.put_nowait(f)
  454. if not todo and timeout_handle is not None:
  455. timeout_handle.cancel()
  456. async def _wait_for_one():
  457. f = await done.get()
  458. if f is None:
  459. # Dummy value from _on_timeout().
  460. raise futures.TimeoutError
  461. return f.result() # May raise f.exception().
  462. for f in todo:
  463. f.add_done_callback(_on_completion)
  464. if todo and timeout is not None:
  465. timeout_handle = loop.call_later(timeout, _on_timeout)
  466. for _ in range(len(todo)):
  467. yield _wait_for_one()
  468. @types.coroutine
  469. def __sleep0():
  470. """Skip one event loop run cycle.
  471. This is a private helper for 'asyncio.sleep()', used
  472. when the 'delay' is set to 0. It uses a bare 'yield'
  473. expression (which Task.__step knows how to handle)
  474. instead of creating a Future object.
  475. """
  476. yield
  477. async def sleep(delay, result=None, *, loop=None):
  478. """Coroutine that completes after a given time (in seconds)."""
  479. if delay <= 0:
  480. await __sleep0()
  481. return result
  482. if loop is None:
  483. loop = events.get_event_loop()
  484. future = loop.create_future()
  485. h = loop.call_later(delay,
  486. futures._set_result_unless_cancelled,
  487. future, result)
  488. try:
  489. return await future
  490. finally:
  491. h.cancel()
  492. def ensure_future(coro_or_future, *, loop=None):
  493. """Wrap a coroutine or an awaitable in a future.
  494. If the argument is a Future, it is returned directly.
  495. """
  496. if coroutines.iscoroutine(coro_or_future):
  497. if loop is None:
  498. loop = events.get_event_loop()
  499. task = loop.create_task(coro_or_future)
  500. if task._source_traceback:
  501. del task._source_traceback[-1]
  502. return task
  503. elif futures.isfuture(coro_or_future):
  504. if loop is not None and loop is not futures._get_loop(coro_or_future):
  505. raise ValueError('loop argument must agree with Future')
  506. return coro_or_future
  507. elif inspect.isawaitable(coro_or_future):
  508. return ensure_future(_wrap_awaitable(coro_or_future), loop=loop)
  509. else:
  510. raise TypeError('An asyncio.Future, a coroutine or an awaitable is '
  511. 'required')
  512. @coroutine
  513. def _wrap_awaitable(awaitable):
  514. """Helper for asyncio.ensure_future().
  515. Wraps awaitable (an object with __await__) into a coroutine
  516. that will later be wrapped in a Task by ensure_future().
  517. """
  518. return (yield from awaitable.__await__())
  519. class _GatheringFuture(futures.Future):
  520. """Helper for gather().
  521. This overrides cancel() to cancel all the children and act more
  522. like Task.cancel(), which doesn't immediately mark itself as
  523. cancelled.
  524. """
  525. def __init__(self, children, *, loop=None):
  526. super().__init__(loop=loop)
  527. self._children = children
  528. self._cancel_requested = False
  529. def cancel(self):
  530. if self.done():
  531. return False
  532. ret = False
  533. for child in self._children:
  534. if child.cancel():
  535. ret = True
  536. if ret:
  537. # If any child tasks were actually cancelled, we should
  538. # propagate the cancellation request regardless of
  539. # *return_exceptions* argument. See issue 32684.
  540. self._cancel_requested = True
  541. return ret
  542. def gather(*coros_or_futures, loop=None, return_exceptions=False):
  543. """Return a future aggregating results from the given coroutines/futures.
  544. Coroutines will be wrapped in a future and scheduled in the event
  545. loop. They will not necessarily be scheduled in the same order as
  546. passed in.
  547. All futures must share the same event loop. If all the tasks are
  548. done successfully, the returned future's result is the list of
  549. results (in the order of the original sequence, not necessarily
  550. the order of results arrival). If *return_exceptions* is True,
  551. exceptions in the tasks are treated the same as successful
  552. results, and gathered in the result list; otherwise, the first
  553. raised exception will be immediately propagated to the returned
  554. future.
  555. Cancellation: if the outer Future is cancelled, all children (that
  556. have not completed yet) are also cancelled. If any child is
  557. cancelled, this is treated as if it raised CancelledError --
  558. the outer Future is *not* cancelled in this case. (This is to
  559. prevent the cancellation of one child to cause other children to
  560. be cancelled.)
  561. """
  562. if not coros_or_futures:
  563. if loop is None:
  564. loop = events.get_event_loop()
  565. outer = loop.create_future()
  566. outer.set_result([])
  567. return outer
  568. def _done_callback(fut):
  569. nonlocal nfinished
  570. nfinished += 1
  571. if outer.done():
  572. if not fut.cancelled():
  573. # Mark exception retrieved.
  574. fut.exception()
  575. return
  576. if not return_exceptions:
  577. if fut.cancelled():
  578. # Check if 'fut' is cancelled first, as
  579. # 'fut.exception()' will *raise* a CancelledError
  580. # instead of returning it.
  581. exc = futures.CancelledError()
  582. outer.set_exception(exc)
  583. return
  584. else:
  585. exc = fut.exception()
  586. if exc is not None:
  587. outer.set_exception(exc)
  588. return
  589. if nfinished == nfuts:
  590. # All futures are done; create a list of results
  591. # and set it to the 'outer' future.
  592. results = []
  593. for fut in children:
  594. if fut.cancelled():
  595. # Check if 'fut' is cancelled first, as
  596. # 'fut.exception()' will *raise* a CancelledError
  597. # instead of returning it.
  598. res = futures.CancelledError()
  599. else:
  600. res = fut.exception()
  601. if res is None:
  602. res = fut.result()
  603. results.append(res)
  604. if outer._cancel_requested:
  605. # If gather is being cancelled we must propagate the
  606. # cancellation regardless of *return_exceptions* argument.
  607. # See issue 32684.
  608. outer.set_exception(futures.CancelledError())
  609. else:
  610. outer.set_result(results)
  611. arg_to_fut = {}
  612. children = []
  613. nfuts = 0
  614. nfinished = 0
  615. for arg in coros_or_futures:
  616. if arg not in arg_to_fut:
  617. fut = ensure_future(arg, loop=loop)
  618. if loop is None:
  619. loop = futures._get_loop(fut)
  620. if fut is not arg:
  621. # 'arg' was not a Future, therefore, 'fut' is a new
  622. # Future created specifically for 'arg'. Since the caller
  623. # can't control it, disable the "destroy pending task"
  624. # warning.
  625. fut._log_destroy_pending = False
  626. nfuts += 1
  627. arg_to_fut[arg] = fut
  628. fut.add_done_callback(_done_callback)
  629. else:
  630. # There's a duplicate Future object in coros_or_futures.
  631. fut = arg_to_fut[arg]
  632. children.append(fut)
  633. outer = _GatheringFuture(children, loop=loop)
  634. return outer
  635. def shield(arg, *, loop=None):
  636. """Wait for a future, shielding it from cancellation.
  637. The statement
  638. res = await shield(something())
  639. is exactly equivalent to the statement
  640. res = await something()
  641. *except* that if the coroutine containing it is cancelled, the
  642. task running in something() is not cancelled. From the POV of
  643. something(), the cancellation did not happen. But its caller is
  644. still cancelled, so the yield-from expression still raises
  645. CancelledError. Note: If something() is cancelled by other means
  646. this will still cancel shield().
  647. If you want to completely ignore cancellation (not recommended)
  648. you can combine shield() with a try/except clause, as follows:
  649. try:
  650. res = await shield(something())
  651. except CancelledError:
  652. res = None
  653. """
  654. inner = ensure_future(arg, loop=loop)
  655. if inner.done():
  656. # Shortcut.
  657. return inner
  658. loop = futures._get_loop(inner)
  659. outer = loop.create_future()
  660. def _inner_done_callback(inner):
  661. if outer.cancelled():
  662. if not inner.cancelled():
  663. # Mark inner's result as retrieved.
  664. inner.exception()
  665. return
  666. if inner.cancelled():
  667. outer.cancel()
  668. else:
  669. exc = inner.exception()
  670. if exc is not None:
  671. outer.set_exception(exc)
  672. else:
  673. outer.set_result(inner.result())
  674. def _outer_done_callback(outer):
  675. if not inner.done():
  676. inner.remove_done_callback(_inner_done_callback)
  677. inner.add_done_callback(_inner_done_callback)
  678. outer.add_done_callback(_outer_done_callback)
  679. return outer
  680. def run_coroutine_threadsafe(coro, loop):
  681. """Submit a coroutine object to a given event loop.
  682. Return a concurrent.futures.Future to access the result.
  683. """
  684. if not coroutines.iscoroutine(coro):
  685. raise TypeError('A coroutine object is required')
  686. future = concurrent.futures.Future()
  687. def callback():
  688. try:
  689. futures._chain_future(ensure_future(coro, loop=loop), future)
  690. except Exception as exc:
  691. if future.set_running_or_notify_cancel():
  692. future.set_exception(exc)
  693. raise
  694. loop.call_soon_threadsafe(callback)
  695. return future
  696. # WeakSet containing all alive tasks.
  697. _all_tasks = weakref.WeakSet()
  698. # Dictionary containing tasks that are currently active in
  699. # all running event loops. {EventLoop: Task}
  700. _current_tasks = {}
  701. def _register_task(task):
  702. """Register a new task in asyncio as executed by loop."""
  703. _all_tasks.add(task)
  704. def _enter_task(loop, task):
  705. current_task = _current_tasks.get(loop)
  706. if current_task is not None:
  707. raise RuntimeError(f"Cannot enter into task {task!r} while another "
  708. f"task {current_task!r} is being executed.")
  709. _current_tasks[loop] = task
  710. def _leave_task(loop, task):
  711. current_task = _current_tasks.get(loop)
  712. if current_task is not task:
  713. raise RuntimeError(f"Leaving task {task!r} does not match "
  714. f"the current task {current_task!r}.")
  715. del _current_tasks[loop]
  716. def _unregister_task(task):
  717. """Unregister a task."""
  718. _all_tasks.discard(task)
  719. _py_register_task = _register_task
  720. _py_unregister_task = _unregister_task
  721. _py_enter_task = _enter_task
  722. _py_leave_task = _leave_task
  723. try:
  724. from _asyncio import (_register_task, _unregister_task,
  725. _enter_task, _leave_task,
  726. _all_tasks, _current_tasks)
  727. except ImportError:
  728. pass
  729. else:
  730. _c_register_task = _register_task
  731. _c_unregister_task = _unregister_task
  732. _c_enter_task = _enter_task
  733. _c_leave_task = _leave_task