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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://doc.rust-lang.org/error_codes/E0706.html

解决方案

  1. 在 await 点之前克隆线程局部值:`let val = THREAD_LOCAL.with(|v| v.clone());` 然后在 await 后使用 `val`。
  2. 重构代码以避免跨 await 持有借用:使用 `let result = { THREAD_LOCAL.with(|v| v.do_something()) }; result.await`。

无效尝试

常见但无效的做法:

  1. Wrapping the thread-local in `Rc` to extend lifetime 85% 失败

    `Rc` is not `Send`, so cannot be used across await points in async contexts.

  2. Using `unsafe` to extend the borrow lifetime manually 90% 失败

    Undefined behavior; compiler may still reject or cause data races.