asyncio 学习
1.协程
协程函数: 定义形式为 async def 的函数;
协程对象: 调用 协程函数 所返回的对象。
2.创建任务
asyncio.create_task(coro, *, name=None)
将 coro 协程 封装为一个 Task 并调度其执行。返回 Task 对象。
3.并发运行任务
asyncio.gather(*aws, return_exceptions=False)
并发 运行 aws 序列中的 可等待对象。
import asyncio
import time
import json
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
# async def main():
# print(f"started at {time.strftime('%X')}")
# await say_after(1, 'hello')
# await say_after(2, 'world')
# print(f"finished at {time.strftime('%X')}")
# async def main():
# print(f"started at {time.strftime('%X')}")
# task1 = asyncio.create_task(say_after(1, 'hello'))
# task2 = asyncio.create_task(say_after(2, 'world'))
# await task1
# await asyncio.sleep(1)
# await task2
# print(f"finished at {time.strftime('%X')}")
async def main():
print(f"started at {time.strftime('%X')}")
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
await asyncio.gather(task1, asyncio.sleep(1), task2)
tasks = list()
for i in range(1, 100):
task = asyncio.create_task(say_after(2, f'hello{i}'))
tasks.append(task)
await asyncio.gather(*tasks)
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
参考官方文档:https://docs.python.org/zh-cn/3/library/asyncio-task.html
如何使用 asyncio 限制协程的并发数: https://www.cnblogs.com/kcxg/p/15107785.html
浙公网安备 33010602011771号