我刚刚开始学习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
为什么不打印“世界”?
答案 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