1. 程式人生 > 其它 >協程的巢狀

協程的巢狀

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