如何在锈中创建RwLock的向量?

时间:2019-07-18 13:50:49

标签: rust automatic-ref-counting readwritelock

我需要构造一个向量。向量的每个元素都必须受RwLock保护。线程需要在此向量中读写(感谢RwLock)。如何在Rust中做到这一点。

我尝试使用Arc向量。

#[derive(Default, Debug, Clone, Copy)]
pub struct shared_values {
    x: usize,
    y: usize,
}

fn main() {
    let mut shared = vec![Arc::new(RwLock::new(shared_values { x: 0, y: 0 })); 10];

    //changing value of the element [0]
    {
        let mut sh = shared[0].write().unwrap();
        *sh = shared_values { x: 10, y: 10 };
    }

    //Printing
    {
        println!("Print RwLock");
        for i in 0..g.ns {
            {
                let val = shared[i].read().unwrap();
                println!("{:?}", val);
            }
        }
    }
}

结果是这样的:

RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }
RwLockReadGuard { lock: RwLock { data: shared_values { suitor: 10, ws: 10 } } }

我希望将元素0设置为{x:10,y:10}

我认为Arc可以增加shared_values {x:0,y:0}的计数参考,但是不会为向量中的每个索引创建独立元素。

1 个答案:

答案 0 :(得分:1)

此向量初始化将克隆参数。使用std::iter::repeat_with

use std::sync::{Arc, RwLock};

#[derive(Default, Debug, Clone, Copy)]
pub struct SharedValues {
    x: usize,
    y: usize,
}

fn main() {
    let shared: Vec<_> =
        std::iter::repeat_with(|| Arc::new(RwLock::new(SharedValues { x: 0, y: 0 })))
            .take(10)
            .collect();

    //changing value of the element [0]
    {
        let mut sh = shared[0].write().unwrap();
        *sh = SharedValues { x: 10, y: 10 };
    }

    //Printing
    {
        println!("Print RwLock");
        for x in shared {
            println!("{:?}", x.read().unwrap());
        }
    }
}

如果您错过了宏的简单性,则可以编写自己的宏:

macro_rules! vec_no_clone {
    ( $val:expr; $n:expr ) => {{
        let result: Vec<_> = std::iter::repeat_with(|| $val).take($n).collect();
        result
    }};
}

fn main() {
    let shared = vec_no_clone![Arc::new(RwLock::new(SharedValues { x: 0, y: 0 })); 10];
}