rust - 可以是“发送”的 RefCell 替代方案?
问题描述
我正在设计一种可以在线程之间发送或不发送的类型,这取决于它是否是 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
?
解决方案
我知道这不是发送,因为 RefCell 是!发送。我认为这是阻止 M 发送的唯一原因。
是的,这是正确的。
是否有发送的 RefCell 替代方案?
当然,至少有两个。如果你只想&mut
在另一个线程中,你实际上可以发送它:
#[derive(Debug)]
pub enum M<'a, T> {
Owned(),
Ref(&'a mut [T])
}
fn main() {
let m: M<'static, u8> = M::Owned();
std::thread::spawn(move ||{
println!("{:?}", m);
}).join().unwrap();
}
但是,如果您使用Rc<RefCell<_>>
to 例如使您的&mut
可共享,您可以在多线程上下文中实现相同的事情Arc<Mutex<_>>
,正如@Locke 已经提到的:
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone)]
pub enum M<'a, T> {
Owned(),
Ref(Arc<Mutex<&'a mut [T]>>)
}
fn main() {
let m: M<'static, u8> = M::Owned();
let m2 = m.clone();
std::thread::spawn(move ||{
println!("{:?}", m2);
}).join().unwrap();
println!("{:?}", m);
}
推荐阅读
- modelsim - 无法在 modelsim 中创建项目
- android-studio - 如何在android的新活动中转换片段?
- swift - 有没有办法在 Swift 中延迟返回语句?
- python - 美丽的汤有时返回 NoneType
- python - Python 熊猫 .transform
- c# - 我可以更改列表的显示方式,但在自定义编辑器中保留 Add(-) 和 Remove(+) 按钮吗?
- node.js - 在 Node.js 中为数组的每个元素编写一个文件
- java - 使用 Streams 直接将属性转换为 HashMap
- c - 从递归函数打印主函数
- c++ - 如何重新映射 YUY2 图像?