【问题标题】:Why does `await asyncio.create_task()` behave different then when assigning it to a variable?为什么`await asyncio.create_task()`的行为与将其分配给变量时不同?
【发布时间】:2020-01-12 18:37:38
【问题描述】:

为什么在下面的代码中任务 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

【问题讨论】:

    标签: python python-3.x python-asyncio python-3.8


    【解决方案1】:

    在第一个 sn-p 中,您立即等待您创建的每个任务。因此,这些任务无法并行运行。

    在第二个 sn-p 中,您创建了三个任务,然后才开始等待。这允许所有三个并行运行,尽管您的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
    

    ...你会得到与第一个示例类似的行为。

    【讨论】:

      猜你喜欢
      • 2016-02-10
      • 2022-10-05
      • 1970-01-01
      • 2018-03-01
      • 2021-01-12
      • 2014-12-05
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多