python
runtime_error
ai_generated
true
RuntimeError: <asyncio.locks.Semaphore object at 0x...> is bound to a different event loop
ID: python/asyncio-semaphore-bound-in-different-loop
80%Fix Rate
87%Confidence
0Evidence
2024-12-03First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8+ | active | — | — | — |
| 3.9+ | active | — | — | — |
| 3.10+ | active | — | — | — |
| 3.11+ | active | — | — | — |
| 3.12+ | active | — | — | — |
Root Cause
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.
generic中文
在某个事件循环下创建的 asyncio 同步原语(Semaphore、Lock、Event、Queue)被另一个循环使用,常见于跨 asyncio.run() 调用复用模块级原语。
Workarounds
-
95% success
async def main(): sem = asyncio.Semaphore(10) # created inside the loop await run_all(sem) asyncio.run(main()) -
90% success
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(main()) # reuse loop; do not call asyncio.run() repeatedly
Dead Ends
Common approaches that don't work:
-
85% fail
Private attribute hack; the semaphore's internal waiters still reference the old loop.
-
80% fail
The primitive is still bound to its original loop; new loop does not fix it.