# 运行时错误：信号量释放次数过多

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

## 根因

信号量被释放的次数超过了获取次数，通常是由于在 finally 块中释放而未检查是否已获取。

## 版本兼容性

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

## 解决方案

1. **Use context manager for semaphore to ensure proper acquire/release** (95% 成功率)
   ```
   async with semaphore: await some_coroutine()
   ```
2. **Use a try-finally block with a flag to track acquisition** (90% 成功率)
   ```
   acquired = await semaphore.acquire(); try: await some_coroutine(); finally: if acquired: semaphore.release()
   ```

## 无效尝试

- **Increasing the initial semaphore value** — This masks the bug but does not fix the logic; over-release still occurs. (60% 失败率)
- **Using semaphore.acquire() without await** — acquire() returns a coroutine; not awaiting it leads to incorrect behavior. (80% 失败率)
