我有一个结构不是Send因为它包含Rc. 可以说Arc开销太大,所以我想继续使用Rc. 我仍然希望偶尔Send在线程之间使用这个结构,但只有当我可以验证Rc具有 strong_count 1 和 weak_count 0 时。
这是我想到的(希望是安全的)抽象:
mod my_struct {
use std::rc::Rc;
#[derive(Debug)]
pub struct MyStruct {
reference_counted: Rc<String>,
// more fields...
}
impl MyStruct {
pub fn new() -> Self {
MyStruct {
reference_counted: Rc::new("test".to_string())
}
}
pub fn pack_for_sending(self) -> Result<Sendable, Self> {
if Rc::strong_count(&self.reference_counted) == 1 &&
Rc::weak_count(&self.reference_counted) == 0
{
Ok(Sendable(self))
} else {
Err(self)
}
}
// There are more …Run Code Online (Sandbox Code Playgroud)