python runtime_error ai_generated true

asyncpg.exceptions.InterfaceError: 无法执行操作:另一个操作正在进行中

asyncpg.exceptions.InterfaceError: cannot perform operation: another operation is in progress

ID: python/asyncpg-cannot-perform-operation-another-operation-in-progress

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

版本兼容性

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

根因分析

两个协程并发使用了同一个 asyncpg 连接。asyncpg 连接不是并发安全的,同一时间只能由一个协程使用。

English

Two coroutines used the same asyncpg connection concurrently. asyncpg connections are not concurrency-safe; each must be used by one coroutine at a time.

generic

解决方案

  1. 95% 成功率
    pool = await asyncpg.create_pool(dsn, min_size=1, max_size=10)
    async with pool.acquire() as conn:
        await conn.fetch('SELECT 1')
  2. 90% 成功率
    lock = asyncio.Lock()
    async with lock:
        await conn.fetch(query)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Does not serialize access; race still occurs under load.

  2. 75% 失败

    Retries can still collide with the same concurrent coroutine and corrupt protocol state.