await 如何在 for 循环中工作?
How does await works in a for-loop?
我刚刚在 youtube 上看了一个 async/await
tutorial video。
根据我对await
的理解,如果await
在任务中,当执行任务时它会在遇到await
内部时返回事件循环任务。
所以如果 await
在 for 循环中(也就是说 10 个循环),任务将暂停 10 次,我应该在事件循环中使用 10 await
以便完成任务,像这样:
import asyncio
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(0.25)
async def main():
task2 = asyncio.create_task(print_numbers())
for i in range(10):
await task2
asyncio.run(main())
但是,实际上只用1个await
就可以完成任务,像这样:
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(0.25)
async def main():
task2 = asyncio.create_task(print_numbers())
await task2
asyncio.run(main()
我在这个主题中遗漏了什么?
it would turn back to the event-loop while it encounter the await
inside of the task
确实如此,但是在开始任务 [1] 之前,您需要等待任务 [0] 完成,因此事件循环中根本没有其他任务可执行。所以你的代码最终只是睡觉什么都不做
and I should use 10 await
in the event-loop in order to finished the task
是的,您需要等待您开始的 10 个任务,因此您的代码只会在所有 10 个任务完成后继续。但是您应该使用 asyncio.wait
或 asyncio.gather
这样各个任务就可以并行化 而不必等待前一个任务完成。
import asyncio
import random
async def print_number(i):
print(i, 'start')
await asyncio.sleep(random.random())
print(i, 'done')
async def main():
await asyncio.wait([
asyncio.create_task(print_number(i))
for i in range(10)
])
print('main done')
asyncio.run(main())
我刚刚在 youtube 上看了一个 async/await
tutorial video。
根据我对await
的理解,如果await
在任务中,当执行任务时它会在遇到await
内部时返回事件循环任务。
所以如果 await
在 for 循环中(也就是说 10 个循环),任务将暂停 10 次,我应该在事件循环中使用 10 await
以便完成任务,像这样:
import asyncio
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(0.25)
async def main():
task2 = asyncio.create_task(print_numbers())
for i in range(10):
await task2
asyncio.run(main())
但是,实际上只用1个await
就可以完成任务,像这样:
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(0.25)
async def main():
task2 = asyncio.create_task(print_numbers())
await task2
asyncio.run(main()
我在这个主题中遗漏了什么?
it would turn back to the event-loop while it encounter the
await
inside of the task
确实如此,但是在开始任务 [1] 之前,您需要等待任务 [0] 完成,因此事件循环中根本没有其他任务可执行。所以你的代码最终只是睡觉什么都不做
and I should use 10
await
in the event-loop in order to finished the task
是的,您需要等待您开始的 10 个任务,因此您的代码只会在所有 10 个任务完成后继续。但是您应该使用 asyncio.wait
或 asyncio.gather
这样各个任务就可以并行化 而不必等待前一个任务完成。
import asyncio
import random
async def print_number(i):
print(i, 'start')
await asyncio.sleep(random.random())
print(i, 'done')
async def main():
await asyncio.wait([
asyncio.create_task(print_number(i))
for i in range(10)
])
print('main done')
asyncio.run(main())