python
runtime_error
ai_generated
true
RuntimeError: <asyncio.locks.Semaphore object at 0x...> 绑定到不同的事件循环
RuntimeError: <asyncio.locks.Semaphore object at 0x...> is bound to a different event loop
ID: python/asyncio-semaphore-bound-in-different-loop
80%修复率
87%置信度
0证据数
2024-12-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8+ | active | — | — | — |
| 3.9+ | active | — | — | — |
| 3.10+ | active | — | — | — |
| 3.11+ | active | — | — | — |
| 3.12+ | active | — | — | — |
根因分析
在某个事件循环下创建的 asyncio 同步原语(Semaphore、Lock、Event、Queue)被另一个循环使用,常见于跨 asyncio.run() 调用复用模块级原语。
English
An asyncio synchronization primitive (Semaphore, Lock, Event, Queue) was created under one loop and used under another, common when module-level primitives are reused across asyncio.run() calls.
解决方案
-
95% 成功率
async def main(): sem = asyncio.Semaphore(10) # created inside the loop await run_all(sem) asyncio.run(main()) -
90% 成功率
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(main()) # reuse loop; do not call asyncio.run() repeatedly
无效尝试
常见但无效的做法:
-
85% 失败
Private attribute hack; the semaphore's internal waiters still reference the old loop.
-
80% 失败
The primitive is still bound to its original loop; new loop does not fix it.