AIGC标识 asyncio

语法 作用 示例
async def 定义协程函数 async def fetch(): ...
await 挂起协程,等待结果 result = await fetch()
async with 异步上下文管理器 async with session.get() as resp:
async for 异步迭代器 async for row in cursor: ...

--并发执行:3 个查询同时发出,总耗时 ≈ max(三者)
results = await asyncio.gather(
executor.execute("SELECT * FROM users"),
executor.execute("SELECT * FROM orders"),
executor.execute("SELECT * FROM products"),
)

--带异常处理的并发(某个失败不影响其他)
results = await asyncio.gather(*tasks, return_exceptions=True)

--TaskGroup(Python 3.11+,推荐替代 gather)
async with asyncio.TaskGroup() as tg:
t1 = tg.create_task(executor.execute(sql1))
t2 = tg.create_task(executor.execute(sql2))
--退出 with 块时自动等待所有任务完成,任一异常会取消其余任务

--信号量限流(你的 SQLExecutor 就在用这个)
sem = asyncio.Semaphore(10)
async with sem:
await executor.execute(sql)

--超时保护
async with asyncio.timeout(5.0): # Python 3.11+
await executor.execute(slow_sql)

posted @ 2026-08-03 15:11  不知者buwei  阅读(0)  评论(0)    收藏  举报