How to modify each section of a vector in multiple threads [duplicate]

╄→尐↘猪︶ㄣ 提交于 2021-02-08 08:01:30

问题


I have a vector of u8 and I need to fill this vector with values that can be computed in parallel:

let vector: Vec<u8> = vec![0, len];

Given n_threads threads, each thread can take care of a section of the vector. The only way I know of to pass a mutable vector into multiple threads is to wrap it into a Mutex:

let vector: Arc::new(Mutex::new(vec![0, len]));

and for each thread move the clone of the atomic reference:

for _ in 0..n_hthreads {
    let vector = Arc::clone(&vector);
    thread::spawn(move || fill_vector());
}

The problem with this approach is that I would need to lock the entire vector inside the threads (which completely nullifies the parallelism):

fn fill_vector() {
    let vector = vector.lock().unwrap();
    vector[i] = /* ... */;
}

A possible alternative would be to have multiple vectors and pass each vector to each thread, and once the threads are joined concatenate the vectors, but that would require additional memory unless there is a way to move the sub-vectors into the final vector instead of copying them.

Is there any alternative that would allow me to lock only a specific section of the vector or to move multiple sub-vectors when concatenating (my goal is to have a single vector in the end), or any other alternative to safely write into the vector?

来源:https://stackoverflow.com/questions/52523237/how-to-modify-each-section-of-a-vector-in-multiple-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!