gpt4 book ai didi

multithreading - 将矩阵 (Vec>) 只读传递给多个线程

转载 作者:行者123 更新时间:2023-11-29 08:14:35 25 4
gpt4 key购买 nike

我是 Rust 的新手,我正在为借用的概念而苦苦挣扎。

我想加载 Vec<Vec<f64>>矩阵,然后并行处理它。但是,当我尝试编译这段代码时,我得到了 error: capture of moved value: `matrix` [E0382]let _ =行。

这个矩阵对于线程来说应该是只读的,他们不会修改它。如何以只读方式传递它并消除“移动值”错误?

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);
}

最佳答案

将要共享的对象包装到 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);
}

关于multithreading - 将矩阵 (Vec<Vec<f64>>) 只读传递给多个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36119811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com