为什么在下面的代码中,任务1-3和任务4-6的运行方式会有所不同?
代码:
import asyncio
async def do_something(i, sleep): # No I/O here
print("Doing... ", end="")
print(await no_io_1(i, sleep))
async def no_io_1(i, sleep): # No I/O here
return await no_io_2(i, sleep)
async def no_io_2(i, sleep): # No I/O here
return await io(i, sleep)
async def io(i, sleep):
await asyncio.sleep(sleep) # Finally some I/O
# t = asyncio.create_task(asyncio.sleep(sleep))
# await t
return i
async def main():
await asyncio.create_task(do_something(1, sleep=4))
await asyncio.create_task(do_something(2, sleep=3))
await asyncio.create_task(do_something(3, sleep=2))
t4 = asyncio.create_task(do_something(4, sleep=4))
t5 = asyncio.create_task(do_something(5, sleep=3))
t6 = asyncio.create_task(do_something(6, sleep=2))
await t4
await t5
await t6
asyncio.run(main())
print("\r\nBye!")输出:
Doing... 1
Doing... 2
Doing... 3
Doing... Doing... Doing... 6
5
4发布于 2020-01-13 02:49:26
在第一个代码片段中,您将立即等待您创建的每个任务。结果,任务被阻止并行运行。
在第二个代码片段中,您创建了三个任务,然后才开始等待。这允许这三个函数并行运行,尽管您await指定您对第一个函数的结果感兴趣。(能够在等待特定任务的结果的同时运行其他任务,这是asyncio等库的核心设计目标。)
换句话说,await t1并不意味着“运行t1",它意味着”挂起我并旋转事件循环,直到t1完成“。不同之处与存储在变量中的任务无关,而是一次性创建任务。例如,您可以像这样修改第二个示例:
t4 = asyncio.create_task(do_something(4, sleep=4))
await t4
t5 = asyncio.create_task(do_something(5, sleep=3))
await t5
t6 = asyncio.create_task(do_something(6, sleep=2))
await t6...and,你会得到类似于第一个例子的行为。
https://stackoverflow.com/questions/59706978
复制相似问题