asyncio.Semaphore是协程安全的信号量,用于限制并发协程数;不能用threading.Semaphore替代,因其会阻塞事件循环,导致死锁和警告。

asyncio.Semaphore 是什么,为什么不能直接用 threading.Semaphore
asyncio.Semaphore 是 asyncio 原生的协程安全信号量,用于控制同时运行的协程数量。它和 threading.Semaphore 完全不兼容——后者在 await 点会阻塞整个事件循环,导致所有并发请求卡死。常见错误现象是:设了 5 个并发,但实际只发了 1–2 个请求就停住,RuntimeWarning: coroutine 'Semaphore.acquire' was never awaited 这类警告也常伴随出现。
必须确保:
- 所有
acquire()和release()都在 async 函数内、用await调用 - 每个
acquire()必须配对一个release(),推荐用async with semaphore:自动管理 - 信号量实例应在所有协程共享的作用域创建(如全局、函数外或 session 上下文),不能每次请求都新建
正确封装带限流的 HTTP 请求协程
以 aiohttp 为例,最简可靠写法是把 semaphore 作为参数传入请求函数,并用 async with 包裹关键逻辑:
import asyncio
import aiohttp
<p>semaphore = asyncio.Semaphore(3) # 全局限制最多 3 个并发</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><p>async def fetch_url(session, url):
async with semaphore: # 这里会等待直到有可用许可
try:
async with session.get(url, timeout=10) as resp:
return await resp.text()
except Exception as e:
return f"error: {e}"</p><p>async def main():
urls = ["<a href="https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c">https://www.php.cn/link/5f69e19efaba426d62faeab93c308f5c</a>"] <em> 10
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await asyncio.gather(</em>tasks)
print(len(results))
注意:semaphore 必须在 main() 外定义,否则每次调用 main() 都新建一个,失去限流意义;async with semaphore: 内部自动处理 acquire/release,比手动调用更安全。
与 aiohttp.TCPConnector 的 max_connections 混用时的冲突点
aiohttp.TCPConnector(max_connections=5) 和 asyncio.Semaphore(3) 同时存在时,实际并发数由更严格的那个决定——但它们作用层级不同:前者限制 TCP 连接池大小,后者限制协程进入网络 I/O 的节奏。容易踩的坑是误以为设了 max_connections=5 就不用 Semaphore,结果大量协程同时调用 session.get(),触发连接池排队甚至超时。
建议策略:
- 先用
asyncio.Semaphore控制「发起请求的协程数」(即业务层并发) - 再用
TCPConnector(max_connections)设为略大于 Semaphore 值(如 Semaphore=3 → max_connections=5),留出缓冲余量 - 避免把两者设成相同值,否则可能因连接复用延迟导致部分协程空等
异常发生时 release 是否会被跳过?
如果不用 async with,而是手动 await semaphore.acquire() 后在 try/except 中忘记 await semaphore.release(),就会造成“许可证泄漏”:可用许可数持续减少,最终所有后续协程永久阻塞。
所以必须:
- 优先使用
async with semaphore:—— 它在任何退出路径(包括异常、return、break)下都会释放 - 若必须手动管理,release 必须放在
finally块中,且确保 await 不被忽略 - 可通过
semaphore._value(非公开属性,仅调试用)临时检查当前剩余许可数,但生产环境别依赖它
真正难调试的是跨多个 await 点的复杂逻辑里混入未捕获异常,这时候 async with 就不只是方便,而是必要。

















