等待未来的对象内部

Sor*_*ary 10 python asynchronous future async-await python-asyncio

有这个简单的代码:

import asyncio

async def main():
    f = asyncio.Future()
    await f

asyncio.run(main())
Run Code Online (Sandbox Code Playgroud)

协程(此处main)可以等待 Future 对象。它基本上会被阻止,直到f有结果或设置异常,或者直到它们被取消。

出于好奇,我想知道“这种等待是如何发生的”?我具体检查了Task.py的 Python 实现def __step()

在最简单的形式中,快乐的情况下,当返回的result是 Future 时,它​​是:

.
.
result = coro.send(None)
.
.
blocking = getattr(result, '_asyncio_future_blocking', None)
.
.
if blocking:   # So `result` is a Future with `_asyncio_future_blocking == True`
    result._asyncio_future_blocking = False
    result.add_done_callback(self.__wakeup, context=self._context)
    self._fut_waiter = result
    if self._must_cancel:
        if self._fut_waiter.cancel(msg=self._cancel_message):
            self._must_cancel = False
Run Code Online (Sandbox Code Playgroud)

我从本节中得到了所有其他答案(例如当它result是裸露的yieldCancellationError发生时等等),除了这个!

result._asyncio_future_blocking因此它将to和 add e 回调设置False为 Future。但这__wakeup仅在 Future 完成但尚未完成时才会被调用。我什么也看不见self._loop.call_soon(self.__step)。我只能说有人在看self._fut_waiter。我不知道故事的其余部分。

Task显然课堂上的评论证明了这一点:

    # An important invariant maintained while a Task not done:
    #
    # - Either _fut_waiter is None, and _step() is scheduled;
    # - or _fut_waiter is some Future, and _step() is *not* scheduled.
    #
    # The only transition from the latter to the former is through
    # _wakeup().  When _fut_waiter is not None, one of its callbacks
    # must be _wakeup().
Run Code Online (Sandbox Code Playgroud)

它是否以某种方式注册到该select函数?如果有人告诉我这些期货在哪里进行检查,我将不胜感激。这些 future 如何与事件循环通信?等候区在哪里?

我看了David Beazley关于 AsyncIO 的演讲,我了解了他的事件循环是如何工作的,但在 AsyncIO 框架中,一切都是 Future 而不是文件描述符或套接字。那么Future的作用是什么?

Atl*_*435 1

首先,我觉得自己没有资格回答你的问题,希望有更多知识的人能够接触到这个话题。但由于还没有其他答案,我将尽力为这个有趣的话题提供合格的答案。

\n

Future 对象是一个可等待的 Object。可等待对象主要将自身安排为任务,即由于asyncio.gatherwait_for等待然而, Future 对象Task 对象的较低级别父对象 。

\n

Task 和 Future 之间的主要区别是:

\n
\n

协程可以等待 Future 对象,直到它们有\n结果或设置异常,或者直到它们被取消。

\n
\n

\n
\n

任务用于在事件循环中运行协程。

\n
\n

上面应该回答了你的问题那么Future的作用是什么?.\n你的下一个问题有点难以回答,但重要的是要注意协程等待 Future 对象。

\n

发现它可能有助于首先理解协程是什么。协程是基于生成器的对象,语法为yield fromand yield,方法为sendand ,throw使这一切都发生。

\n
\n

协程的 throw() 和 send() 方法用于将值推送到类似 Future 的对象中并\n引发错误。

\n
\n

[来源]

\n

但所有这些都没有回答您的问题这些 future 如何与事件循环通信?。事实上没有调度器,通信是通过

\n
\n

使用未来收益和任务收益。

\n
\n

我用于学习 asyncio 的资源:

\n\n