我需要制作一个结构向量。向量的每个元素都必须由 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 } 的计数参考,但不会为向量中的每个索引创建独立元素。