我需要制作一个结构向量。矢量的每个元素都必须由 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 增加了 { x : 0 , y : 0 } shared_values计数引用,但没有为向量中的每个索引创建一个独立的元素。
此向量初始化克隆参数。使用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];
}