协程的嵌套

 

 

# coding: utf-8
# @Time    : 2022-05-17 13:15
# @Author  : AngDH
import asyncio
import time

now = lambda: time.time()


async def task1():
    await asyncio.sleep(1)
    print("task1 done")
    return "task1"


async def task2():
    await asyncio.sleep(1)
    print("task2 done")
    return "task2"


async def task3():
    await asyncio.sleep(1)
    print("task3 done")
    return "task3"


async def main():
    start = now()
    tasks = [task1(), task2(), task3()]
    # 1
    # dones, pendings = await asyncio.wait(tasks)
    # for task in dones:
    #     print("task result:", task.result())
    """异步运行  异步输出"""
    # 2
    # for task in asyncio.as_completed(tasks):
    #     result = await task
    #     print("task result:", result)

    """执行顺序=结果顺序"""

    # 3
    result = await asyncio.gather(*tasks)
    print(result)

    """异步运行,同步输出,结果顺序和传参顺序一致"""

    print("耗时:", now() - start)


asyncio.run(main())

 

posted @ 2022-05-17 21:48  AngDH  阅读(37)  评论(0编辑  收藏  举报