python runtime_error ai_generated true

asyncio.exceptions.TimeoutError: (获取时死锁)信号量跨 await 持有

asyncio.exceptions.TimeoutError: (deadlock in acquire) semaphore held across await

ID: python/asyncio-semaphore-deadlock

其他格式: JSON · Markdown 中文 · English
80%修复率
83%置信度
0证据数
2024-10-08首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.9 active — — —
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

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

English

A coroutine acquired an asyncio.Semaphore and then awaited another coroutine that also tried to acquire the same semaphore, causing a self-deadlock.

generic

解决方案

  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())})

无效尝试

常见但无效的做法:

  1. 70% 失败

    If the same task re-enters, it still deadlocks at count+1.

  2. 60% 失败

    Detects the deadlock but doesn't fix the logic; the underlying work never completes.

  3. 85% 失败

    Same re-entrancy problem, now with count=1.