Python中的`await`是否会产生事件循环? [英] Does `await` in Python yield to the event loop?

查看:60
本文介绍了Python中的`await`是否会产生事件循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当我们在异步Python代码中 await 一个协程时究竟发生了什么,例如:

I was wondering what exactly happens when we await a coroutine in async Python code, for example:

await send_message(string)

(1) send_message 已添加到事件循环中,并且调用协程放弃了对该事件循环的控制,或者

(1) send_message is added to the event loop, and the calling coroutine gives up control to the event loop, or

(2)我们直接跳到 send_message

大多数说明我读到的指向(1),因为它们将调用协程描述为退出.但是我自己的实验表明情况(2)是这样的:我试图在呼叫者之后但在被呼叫者之前运行协程,但无法实现这一目的.

Most explanations I read point to (1), as they describe the calling coroutine as exiting. But my own experiments suggest (2) is the case: I tried to have a coroutine run after the caller but before the callee and could not achieve this.

推荐答案

(2)是正确的,除非您等待诸如 asyncio.Future 之类的实际阻塞操作,否则您不会将控制权返回事件循环.

(2) is correct, you won't return control to event loop unless you await something actually blocking like asyncio.Future.

您可以通过更改默认事件循环实现<来进行检查/a>通过继承.

You can check it by changing default event loop implementation through inheritance.

import asyncio


class TestEventLoop(asyncio.SelectorEventLoop):
    def _run_once(self):
        print('inside event loop')
        super()._run_once()


async def func2():
    print('inside func2()')
    await asyncio.sleep(1)


async def func1():
    print('inside func1()')
    await func2()


async def main():
    print('inside main()')
    await func1()


loop = TestEventLoop()
asyncio.set_event_loop(loop)
try:
    loop.run_until_complete(main())
finally:
    loop.close()

结果:

inside event loop
inside main()
inside func1()
inside func2()
inside event loop
inside event loop
inside event loop

但是请注意,这是默认事件循环实现的详细信息.这意味着不能保证(2)对于每种事件循环都是正确的,并且您不应该依赖此行为.

Note however that this is the detail of implementation of the default event loop. It means there's no guarantee (2) will be true for every kind of event loop and you shouldn't rely on this behavior.

这篇关于Python中的`await`是否会产生事件循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆