我刚刚开始学习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为什么不打印"World"?
发布于 2019-05-05 03:45:43
您需要等待对hello的调用结果,以确保函数hello的整个主体都被执行。call 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.097428560256958https://stackoverflow.com/questions/55986092
复制相似问题