本文我们重点介绍Rust的RwLock读写锁的使用,该RwLock即能锁定读也能锁定写,适合在多线程中使用,下面直接上代码。
use std::thread;
use std::sync::{Arc,RwLock};
fn main(){
let mut v = Arc::new(RwLock::new(vec![1,2,3]));
let mut haddles = vec![];
let mut length = v.read().unwrap().len();
for i in 0..length{
let tv = v.clone();
let h = thread::spawn(move || {
let val = tv.read().unwrap()[i];
let mut p = tv.write().unwrap();
p.push(val*val);
});
haddles.push(h);
}
for i in haddles{
i.join().unwrap();
}
length = v.read().unwrap().len();
for i in 0..length{
println!("{}",v.read().unwrap()[i]);
}
}
知识拓展:有点类似Mutex哦。
/*运行结果
1
2
3
1
9
4
*/