我正在设计一个类型,该类型可以根据是否为 Owned 类型来确定能否在不同线程之间发送。
这段代码:
这段代码:
use std::cell::RefCell;
use std::rc::Rc;
pub enum M<'a, T> {
Owned(),
Ref(Rc<RefCell<&'a mut [T]>>)
}
fn main() {
let m: M<'static, u8> = M::Owned();
std::thread::spawn(||{
let m = m;
});
}
提供
error[E0277]: `Rc<RefCell<&mut [_]>>` cannot be sent between threads safely
--> src/main.rs:11:5
|
11 | std::thread::spawn(||{
| _____^^^^^^^^^^^^^^^^^^_-
| | |
| | `Rc<RefCell<&mut [_]>>` cannot be sent between threads safely
12 | | let m = m;
13 | | });
| |_____- within this `[closure@src/main.rs:11:24: 13:6]`
我理解这不是发送(Send)
,因为RefCell
是!Send
。我认为这是妨碍M
成为发送(Send)
的唯一原因。是否有一个RefCell
的替代品可以发送(Send)
?
Arc<Mutex<T>>
。然而,拥有这个结构似乎会带来更多的问题,不值得。那个生命周期可能会在未来给你带来麻烦。Playground 链接 - LockeM
是“静态”的。然而,我仍然希望支持一些情况,其中它保留了引用,以便可以在同一线程上完成一些操作。 - Guerlando OCs