有这个简单的代码:
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是裸露的yield或CancellationError发生时等等),除了这个! …
我试图在python中围绕async/await.
我是在正确的轨道上吗?
async和@coroutine函数返回coroutine/generator,而不是返回值.await 提取协程/发生器的实际返回值.
async 函数结果(coroutines)意味着要添加到事件循环中.
await 在事件循环和等待的协程之间创建"桥梁"(启用下一个点).@coroutine的yield直接与事件循环通信.(跳过等待结果的直接来电者)
await 只能在异步函数中使用.
yield只能在里面使用@coroutine.(@coroutine= @types.coroutine)