E0706
rust
type_error
ai_generated
partial
错误[E0706]:线程局部变量无法跨越 yield 点借用
error[E0706]: thread-local variable cannot be borrowed across a yield point
ID: rust/e0706-thread-local-cannot-be-borrowed-across-yield
78%修复率
83%置信度
1证据数
2024-02-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.75.0 | active | — | — | — |
| 1.77.0 | active | — | — | — |
| 1.79.0 | active | — | — | — |
根因分析
在异步代码中,对线程局部变量(例如 `thread_local!`)的引用跨越了 `.await` 点,这可能导致线程切换,因此不安全。
English
A reference to a thread-local variable (e.g., `thread_local!`) is held across an `.await` point in async code, which is unsafe because the thread may change.
官方文档
https://doc.rust-lang.org/error_codes/E0706.html解决方案
-
在 await 点之前克隆线程局部值:`let val = THREAD_LOCAL.with(|v| v.clone());` 然后在 await 后使用 `val`。
-
重构代码以避免跨 await 持有借用:使用 `let result = { THREAD_LOCAL.with(|v| v.do_something()) }; result.await`。
无效尝试
常见但无效的做法:
-
Wrapping the thread-local in `Rc` to extend lifetime
85% 失败
`Rc` is not `Send`, so cannot be used across await points in async contexts.
-
Using `unsafe` to extend the borrow lifetime manually
90% 失败
Undefined behavior; compiler may still reject or cause data races.