相关疑难解决方法(0)

如果strong_count 为1 且weak_count 为0,包含`Rc` 的`Send` 结构是否安全?

我有一个结构不是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)

unsafe rust

7
推荐指数
1
解决办法
566
查看次数

标签 统计

rust ×1

unsafe ×1