我是Rust的新手,我正在努力解决借贷问题。
我想加载一个Vec<Vec<f64>>
矩阵,然后并行处理它。但是当我尝试编译这段代码时,我会在error: capture of moved value: `matrix` [E0382]
行获得let _ =
。
这个矩阵应该是线程的只读,他们不会修改它。我怎样才能通过它只读它并使'#34;移动的值&#34;错误消失了?
fn process(matrix: &Vec<Vec<f64>>) {
// do nothing for now
}
fn test() {
let filename = "matrix.tsv";
// loads matrix into a Vec<Vec<f64>>
let mut matrix = load_matrix(filename);
// Determine number of cpus
let ncpus = num_cpus::get();
println!("Number of cpus on this machine: {}", ncpus);
for i in 0..ncpus {
// In the next line the "error: capture of moved value: matrix" happens
let _ = thread::spawn(move || {
println!("Thread number: {}", i);
process(&matrix);
});
}
let d = Duration::from_millis(1000 * 1000);
thread::sleep(d);
}
答案 0 :(得分:3)
将要共享的对象包装到Arc
中,表示原子引用计数(指针)。对于每个线程,克隆此指针并将克隆的所有权传递给线程。当被包装的对象不再被任何东西使用时,它将被解除分配。
fn process(matrix: &Vec<Vec<f64>>) {
// do nothing for now
}
fn test() {
use std::sync::Arc;
let filename = "matrix.tsv";
// loads matrix into a Vec<Vec<f64>>
let mut matrix = Arc::new(load_matrix(filename));
// Determine number of cpus
let ncpus = num_cpus::get();
println!("Number of cpus on this machine: {}", ncpus);
for i in 0..ncpus {
let matrix = matrix.clone();
let _ = thread::spawn(move || {
println!("Thread number: {}", i);
process(&matrix);
});
}
let d = Duration::from_millis(1000 * 1000);
thread::sleep(d);
}