Rust 的多线程安全引用 Arc
作者: 许野平
1 Arc 与 Rc 几乎一样,但是多线程安全的
Arc 与 Rc 类似,唯一不同的地方在于 Arc 是多线程安全的。参见下面的例子:
use std::sync::Arc;
use std::thread;
fn main() {
let nums = Arc::new(vec![0, 1, 2, 3, 4]);
let mut childs = vec![];
for n in 0..5 {
let ns = nums.clone();
let c = thread::spawn(move || println!("{:?}", ns[n]));
childs.push(c);
}
for c in childs {
c.join().unwrap();
}
}
-------------------------------------------------------------------------------
>cargo run
0
2
4
1
3
2 Arc 可以打破只读的魔咒
Arc、Rc 都是只读的共享。但是,这个所谓的只读,仅仅是语法层面的。我们可以构造语法结构上是只读的,但实际上允许修改的数据类型。Mutex 就是一个这样的引用类型。看代码吧:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let nums = Arc::new(Mutex::new(vec![]));
let mut childs = vec![];
for n in 0..5 {
let ns = nums.clone();
let c = thread::spawn(move || {
let mut v = ns.lock().unwrap();
v.push(n);
});
childs.push(c);
}
for c in childs {
c.join().unwrap();
}
println!("{:?}", nums);
}
-------------------------------------------------------------------------------
>cargo run
Mutex { data: [0, 1, 3, 2, 4], poisoned: false, .. }