# asyncio.exceptions.TimeoutError: （获取时死锁）信号量跨 await 持有

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

## 根因

某个协程获取了 asyncio.Semaphore，随后 await 另一个也尝试获取同一信号量的协程，导致自我死锁。

## 版本兼容性

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

## 解决方案

1. **** (90% 成功率)
   ```
   Never hold a semaphore across another acquire of the same semaphore; restructure so the inner call uses a separate limiter:

outer = asyncio.Semaphore(10)
inner = asyncio.Semaphore(10)
   ```
2. **** (75% 成功率)
   ```
   Use a re-entrant pattern with contextvars to track ownership.
   ```
3. **** (85% 成功率)
   ```
   Add structured logging around acquire/release to find the cycle:

async with sem:
    logger.info('acquired', extra={'task': id(asyncio.current_task())})
   ```

## 无效尝试

- **** — If the same task re-enters, it still deadlocks at count+1. (70% 失败率)
- **** — Detects the deadlock but doesn't fix the logic; the underlying work never completes. (60% 失败率)
- **** — Same re-entrancy problem, now with count=1. (85% 失败率)
