等待保证执行顺序吗?

Does await guarantee execution order?

考虑一个单线程 Python 程序。名为 "first" 的协程在 I/O 上被阻塞。后续指令是 "await second." 协程 "second" 是否保证立即执行直到阻塞在 I/O 上?或者,"first" 可以在调用 "second" 之前恢复执行(由于 I/O 操作完成)吗?

Asyncio 实现了一种 second 开始执行的方式,直到它 return 控制事件循环(通常发生在它达到某些 I/O 操作时)并且只有在它 return 之后=13=]可以恢复。我不认为它以某种方式向你保证,但也很难相信这个实现会被改变。

如果出于某种原因您不希望 first 在到达 second 的某个部分之前继续执行,最好明确地使用 Lock 来阻止 first 在你想要的时刻之前执行。

示例显示何时可以更改控制 return 到事件循环和执行流程:

import asyncio


async def async_print(text):
    print(text)


async def first():
    await async_print('first 1')
    await async_print('first 2')
    await asyncio.sleep(0)  # returning control to event loop
    await async_print('first 3')


async def second():
    await async_print('second 1')
    await async_print('second 2')
    await asyncio.sleep(0)  # returning control to event loop
    await async_print('second 3')


async def main():
    asyncio.ensure_future(first())
    asyncio.ensure_future(second())
    await asyncio.sleep(1)


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

输出:

first 1
first 2
second 1
second 2
first 3
second 3