【发布时间】:2020-03-29 19:49:14
【问题描述】:
我对 python 中的 asyncio 有点陌生。我试图运行这个简单的代码,但我不知道为什么会得到这个意外的输出。
我所做的是,在outer 函数中,我创建了异步任务并将其存储在数组tasks 中。在等待这些任务之前,我写了一个打印语句print("outer"),它应该在每次迭代中运行。在任务中,我在inner 函数中写了另一个打印语句print("inner")。但是有些我得到了一些意想不到的输出。
这是代码 -
import asyncio
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(outer(loop))
loop.close()
async def outer(loop):
tasks = []
for i in range(0, 5):
tasks.append(loop.create_task(inner()))
for task in tasks:
print("outer")
await task
async def inner():
print("inner")
await asyncio.sleep(0.5)
if __name__ == '__main__':
main()
这是输出 -
outer
inner
inner
inner
inner
inner
outer
outer
outer
outer
我的预期输出是 -
outer
inner
outer
inner
outer
inner
outer
inner
outer
inner
为什么所有inner 都在outer 之前打印。 asyncio 的正确执行流程是什么?提前致谢。
【问题讨论】:
-
每个任务/协程 runs 直到
await语句然后它被暂停。您的示例类似于文档中的 coroutine example 具有相似的结果。 -
来自the docs -
While a Task is running in the event loop, no other Tasks can run in the same thread. When a Task executes an await expression, the running Task gets suspended, and the event loop executes the next Task. -
但是当一个任务被等待时,为了开始一个新任务,事件循环必须执行下一个
for循环迭代。如果这是真的,那么outer应该已经被打印出来了。
标签: python asynchronous async-await python-asyncio