Asyncio意外输出

时间:2019-05-04 19:26:35

标签: python

我刚刚开始学习python asyncio,下面是我的简单代码:

import asyncio
import time

loop = asyncio.get_event_loop()

async def hello():
    print("Hello")
    await asyncio.sleep(2)
    print("World")

async def main():
    for _ in range(10):
        asyncio.ensure_future(hello())

start_time = time.time()
loop.run_until_complete(main())
duration = time.time() - start_time
print(duration)

但是结果是这样的:

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
0.007950782775878906

为什么不打印“世界”?

1 个答案:

答案 0 :(得分:1)

您需要等待对hello的调用结果,以确保执行函数hello的整个主体。调用loop.run_until_complete(main())会运行事件循环,直到main完成,但是,您的代码不需要在完成hello之前完成对main的调用。您需要明确地使main的终止取决于对hello的所有调用的终止。

您可以使用asyncio.gather来实现所需的行为,如下所示:

import asyncio
import time

loop = asyncio.get_event_loop()

async def hello():
    print("Hello")
    await asyncio.sleep(2)
    print("World")

async def main():
    tasks = []
    for _ in range(10):
      tasks.append(asyncio.ensure_future(hello()))
    await asyncio.gather(*tasks)

start_time = time.time()
loop.run_until_complete(main())
duration = time.time() - start_time
print(duration)

产生:

Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
Hello
World
World
World
World
World
World
World
World
World
World
2.097428560256958