# 值错误：信号量获取次数过多

- **ID:** `python/asyncio-semaphore-acquire-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

asyncio.Semaphore 的释放次数多于获取次数，导致计数器超过初始值。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |

## 解决方案

1. **Use async with for semaphore to ensure balanced acquire/release** (95% 成功率)
   ```
   async with semaphore:
    # limited resource access
   ```
2. **Track acquire count manually to avoid double release** (90% 成功率)
   ```
   acquired = False
try:
    await semaphore.acquire()
    acquired = True
    # use resource
finally:
    if acquired:
        semaphore.release()
   ```

## 无效尝试

- **Increasing the semaphore limit to avoid the error** — This masks the imbalance bug and may lead to resource exhaustion. (40% 失败率)
- **Using a try-finally block that releases unconditionally** — If the semaphore was not acquired due to an exception, releasing it causes the error. (60% 失败率)
