当我在 cpython 3.6 上运行它时,以下程序会打印一次 hello world
,然后永远旋转。
顺便说一句,取消注释 await asyncio.sleep(0)
行会导致它每秒打印 hello world
,这是可以理解的。
import asyncio
async def do_nothing():
# await asyncio.sleep(0)
pass
async def hog_the_event_loop():
while True:
await do_nothing()
async def timer_print():
while True:
print("hello world")
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.create_task(timer_print())
loop.create_task(hog_the_event_loop())
loop.run_forever()
这种行为(一次打印hello world
)对我来说很有意义,因为hog_the_event_loop
永远不会阻塞,因此不需要暂停执行。 我可以依赖这种行为吗? 当 await do_nothing()
行运行时,是否有可能不进入 do_nothing()
协程,执行实际上会挂起并恢复timer_print()
,导致程序再次打印hello world
?
更笼统地说:Python 什么时候会暂停协程的执行并切换到另一个协程?使用 await
关键字是否可能任何?还是仅在导致底层 select
调用(例如 I/O、 sleep 计时器等)的情况下?
额外说明
我明白,如果 hog_the_event_loop
看起来像这样,它肯定不会让另一个协程执行:
async def hog_the_event_loop():
while True:
pass
我正在尝试具体解决 await do_nothing()
是否与上述有任何不同的问题。
最佳答案
This behavior (printing hello world a single time) makes sense to me, because
hog_the_event_loop
never blocks and therefore has no need to suspend execution. Can I rely on this behavior?
是的。此行为直接遵循语言如何指定和实现 await
。将其更改为挂起而不让可等待对象挂起本身肯定是一个重大更改,无论是对于 asyncio and 来说都是如此。 other基于 async/await 的 Python 库。
Put more generally: When will python suspend execution of a coroutine and switch to another one? Is it potentially on any use of the
await
keyword?
从调用者的角度来看,任何 await
都可以潜在挂起,具体取决于等待对象(也称为 awaitable)。 。因此,特定 await
是否挂起的最终决定取决于等待对象(或者如果它是协程,则等待对象等待自身,等等)。等待不选择挂起的等待对象与运行普通 Python 代码相同 - 它不会将控制传递给事件循环。
实际挂起的叶可等待事件通常与 IO 就绪或超时事件相关,但并非总是如此。例如,等待queue如果队列为空,则项目将挂起并等待 run_in_executor
将挂起,直到另一个线程中运行的函数完成。
值得一提的是asyncio.sleep
是explicitly guaranteed暂停执行并推迟到事件循环,即使指定的延迟为 0(在这种情况下,它将在下一个事件循环传递时立即恢复)。
关于python - Python 何时会/不会暂停协程的执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56204040/