# asyncio 异常：锁获取超时

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

## 根因

协程尝试使用超时获取 asyncio.Lock，但锁未在指定时间内释放。

## 版本兼容性

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

## 解决方案

1. **Use async with for lock to ensure automatic release** (95% 成功率)
   ```
   async with lock:
    # critical section
   ```
2. **Implement a retry mechanism with backoff** (85% 成功率)
   ```
   async def acquire_with_retry(lock, timeout=5):
    for i in range(3):
        try:
            await asyncio.wait_for(lock.acquire(), timeout=timeout)
            return
        except asyncio.TimeoutError:
            await asyncio.sleep(1)
   ```

## 无效尝试

- **Increasing the timeout indefinitely** — This may cause the application to hang if the lock is never released. (40% 失败率)
- **Using a try-finally block without ensuring release on cancellation** — If the coroutine is cancelled, the lock may not be released, causing deadlocks. (60% 失败率)
