17-协程的简单使用

  • 阅读: 446
  • 更新: 2022-06-30

协程是子例程的更一般形式。子例程可以在某一点进入并在另一点退出。协程则可以在许多不同的点上进入、退出和恢复。
协程可通过 async def 语句来实现。通过 async/await 语法来声明协程是编写异步应用的推荐方式。
https://docs.python.org/zh-cn/3/library/asyncio-task.html

1. 代码示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import asyncio


async def test(_id):
    print(f'当前{_id}')
    await asyncio.sleep(1)


async def main():
    aws = []  # 存储可等待对象
    for _id in range(10):
        aws.append(test(_id))

    await asyncio.gather(*aws)  # 并发运行

asyncio.run(main())  # 运行 asyncio 程序

运行结果可发现总体仅耗时1秒,而不是10秒


=== 全文完 ===


欢迎加入QQ群:855013471

京公网安备 11011302003970号 京ICP备2022012301号-1