其他分享
首页 > 其他分享> > 协程的嵌套

协程的嵌套

作者:互联网

 

 

# 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())

 

标签:task,协程,await,嵌套,tasks,result,print,asyncio
来源: https://www.cnblogs.com/angdh/p/16282545.html