python
runtime_error
ai_generated
true
运行时错误:任务 <Task pending> 获取了附加到不同循环的 Future <Future pending>
RuntimeError: Task <Task pending> got Future <Future pending> attached to a different loop
ID: python/asyncio-future-attached-to-loop
80%修复率
88%置信度
0证据数
2024-10-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
协程或任务等待了一个属于不同事件循环的 Future,通常是由于跨线程混合循环或在 asyncio.gather 中使用来自不同循环的任务。
English
A coroutine or task awaits a Future that belongs to a different event loop, often due to mixing loops across threads or using asyncio.gather with tasks from different loops.
解决方案
-
90% 成功率 Ensure all coroutines and futures are created in the same event loop
loop = asyncio.new_event_loop(); asyncio.set_event_loop(loop); loop.run_until_complete(main())
-
95% 成功率 Use asyncio.run() to avoid loop conflicts entirely
async def main(): await asyncio.gather(coro1(), coro2()); asyncio.run(main())
无效尝试
常见但无效的做法:
-
Creating a new loop and setting it globally
60% 失败
The Future is still attached to the original loop; global setting does not migrate it.
-
Using asyncio.ensure_future instead of create_task
70% 失败
ensure_future also attaches to the current loop; same issue.