【发布时间】:2017-09-21 09:07:48
【问题描述】:
Safe Rust 要求所有参考资料如下:
- 一个或多个对资源的引用 (
&T), - 正是一个可变引用 (
&mut T)。
我希望有一个Vec 可以被多个线程读取并由一个线程写入,但一次只能有一个线程(根据语言要求)。
所以我使用RwLock。
我需要Vec<i8>。为了让它比 main 函数更长寿,我 Box 它然后我 RwLock 在 that 周围,像这样:
fn main() {
println!("Hello, world!");
let mut v = vec![0, 1, 2, 3, 4, 5, 6];
let val = RwLock::new(Box::new(v));
for i in 0..10 {
thread::spawn(move || threadFunc(&val));
}
loop {
let mut VecBox = (val.write().unwrap());
let ref mut v1 = *(*VecBox);
v1.push(1);
//And be very busy.
thread::sleep(Duration::from_millis(10000));
}
}
fn threadFunc(val: &RwLock<Box<Vec<i8>>>) {
loop {
//Use Vec
let VecBox = (val.read().unwrap());
let ref v1 = *(*VecBox);
println!("{}", v1.len());
//And be very busy.
thread::sleep(Duration::from_millis(1000));
}
}
Rust 拒绝编译这个:
capture of moved value: `val`
--> src/main.rs:14:43
|
14 | thread::spawn(move || threadFunc(&val));
| ------- ^^^ value captured here after move
| |
| value moved (into closure) here
没有线程:
for i in 0..10 {
threadFunc(&val);
}
它编译。问题在于关闭。我必须“移动”它,否则 Rust 抱怨它可以比 main 活得更久,我也不能克隆 val(RwLock 没有实现 clone())。
我该怎么办?
【问题讨论】:
标签: multithreading rust