asyncio.Semaphore是唯一靠谱的协程并发控制方案,必须在协程外创建唯一实例、用await acquire()和try/finally配对release(推荐async with),严禁在循环中重复新建;它控制“发起请求数”,非连接数,合理并发值通常为5~20。

asyncio.Semaphore 是唯一靠谱的选择
直接用 asyncio.Semaphore,别碰 threading.Semaphore 或第三方同步锁——它们在协程里会阻塞整个事件循环。Semaphore 的核心作用是「让最多 N 个协程同时进入临界区」,不是锁资源,而是控并发数。
常见错误是把 semaphore.acquire() 当同步方法调用,结果卡死;必须用 await semaphore.acquire(),且务必配对 semaphore.release()(最好用 try/finally 包裹)。
- 初始化时传入最大并发数,比如
asyncio.Semaphore(5)表示最多 5 个请求并发 - 每个请求前
await semaphore.acquire(),成功后才发 HTTP 请求 - 无论请求成功或抛异常,都必须在
finally中调用semaphore.release() - 不释放会导致后续所有协程永久等待,且无超时机制
HTTP 请求中嵌入 Semaphore 控制的实际写法
以 aiohttp 为例:Semaphore 要定义在 session 外层(如全局或函数外),否则每次新建就失效;不能在每次请求里重新实例化。
import asyncio
import aiohttp
<p>sem = 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><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Camoufox Open Source Anti-Detect Browser for Python Automation" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation">Camoufox Open Source Anti-Detect Browser for Python Automation</a>
<p>Camoufox 是一个基于 Firefox 构建的开源反检测浏览器,为 Python 自动化工作流程提供强大的指纹注入和反机器人检测规避功能。它与 Playwright 集成,以提供能够绕过现代机器人检测系统的隐身浏览能力。</p>
</div>
<a href="/xiazai/skill13278" title="Camoufox Open Source Anti-Detect Browser for Python Automation" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><p>async def fetch(url):
await sem.acquire()
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
return await resp.text()
finally:
sem.release() # 必须放在这里
如果用 httpx.AsyncClient,逻辑一样:Semaphore 管理的是「发起请求」这个动作,跟 client 实例生命周期无关。注意不要把 sem.acquire() 放到 session 创建之后、请求之前——位置错会导致并发控制失效。
为什么不用 asyncio.BoundedSemaphore?
asyncio.BoundedSemaphore 会在 release() 被调用次数超过 acquire() 时抛 ValueError,看似更安全,但实际容易误伤:
- 协程中途被 cancel(比如超时)可能跳过
release(),导致后续 acquire 卡住 - 异常路径没覆盖全(比如
session.get()抛出连接错误前已 acquire)也会引发越界 release - 绝大多数场景下,普通
Semaphore+try/finally更可控、更易 debug
除非你有强审计需求并能保证所有路径都严格配对,否则没必要换。
并发数设多少才合理?
没有固定值,取决于目标服务的承受力和你本地的连接池上限。设太高会触发 429 或连接拒绝;设太低则吞吐上不去。
- 对公开 API(如 GitHub、OpenWeather),通常 2–5 是安全起点
- 内网服务可试 10–50,但要观察
aiohttp的Connector(limit)是否成了瓶颈 - 如果发现大量
ClientOSError: [Errno 24] Too many open files,说明系统文件描述符耗尽,需调低并发或增大 ulimit - 别只看平均响应时间——突发流量下,Semaphore 不会自动降级,得靠外层加熔断或队列缓冲
真正难的不是写对那几行 await acquire(),而是压测时观察服务端返回状态码分布、重试策略是否和 Semaphore 协同工作——这些细节一漏,限流就变成假限流。

















