# RuntimeError: <asyncio.locks.Semaphore object at 0x...> 绑定到不同的事件循环

- **ID:** `python/asyncio-semaphore-bound-in-different-loop`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在某个事件循环下创建的 asyncio 同步原语（Semaphore、Lock、Event、Queue）被另一个循环使用，常见于跨 asyncio.run() 调用复用模块级原语。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8+ | active | — | — |
| 3.9+ | active | — | — |
| 3.10+ | active | — | — |
| 3.11+ | active | — | — |
| 3.12+ | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   async def main():
    sem = asyncio.Semaphore(10)  # created inside the loop
    await run_all(sem)

asyncio.run(main())
   ```
2. **** (90% 成功率)
   ```
   loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())  # reuse loop; do not call asyncio.run() repeatedly
   ```

## 无效尝试

- **** — Private attribute hack; the semaphore's internal waiters still reference the old loop. (85% 失败率)
- **** — The primitive is still bound to its original loop; new loop does not fix it. (80% 失败率)
