Python3.7 高级编程之 async/await asyncio 通过任务gather并发运行协程

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/haeasringnar/article/details/100181731
import asyncio
import time

# 并发执行协程
# 模拟的耗时任务 交给协程来处理
async def my_task(name, number):
    await asyncio.sleep(number)
    print('%s 已经完成任务...' % name)


async def main():
    print(f"started at {time.strftime('%X')}")

    # 将三个任务交给 asyncio.gather 并发的执行 理论的预期:并行耗时应该为 4秒,否则为未达到预期
    await asyncio.gather(
        my_task('A', 2),
        my_task('B', 3),
        my_task('C', 4),
    )

    # 下面的方法和上面可以达到相同的预期 但是 在启动协程较多的情况下 推荐使用上法
    # task1 = asyncio.create_task(my_task('A', 2))
    # task2 = asyncio.create_task(my_task('B', 3))
    # task3 = asyncio.create_task(my_task('C', 4))
    # await task1
    # await task2
    # await task3
    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

猜你喜欢

转载自blog.csdn.net/haeasringnar/article/details/100181731