Hi,
I am trying to use multi-threading on the code below.
I have tried to comment my code so you can understand what I am doing.
1/ The loop to do in parallel is for j in 0..n
. I have tried thread::spawn
but I get a lot of error that I don't understand.
2/ Is there a better (more efficient) way to automatically create chks
which depend on n
and len
.
Sorry in advance if my questions seem dumb. I recently just started with Rust.
Thank you
use rand::Rng;
use rand::distributions::Uniform;
fn main() {
let n = 4; // number of threads
let len = 8; // length of vector
// a random vector of positive integer
let mut rng = rand::thread_rng();
let range = Uniform::new(0, 5);
let x: Vec<u64> = (0..len).map(|_| rng.sample(range)).collect();
let mut counts: Vec<Vec<usize>> = vec![vec![0_usize; len]; n];// a matrix of dim len x n
let chks = vec![[0,1],[2,3],[4,5],[6,7]];// 4 chunks for 4 threads
for j in 0..n { // need to do in parallel
for i in chks[j] { // each thread process its own chunk
counts[j][x[i] as usize] += 1; // each thread writes in its own sub vector
}
}
println!("x = {:?}", x);
println!("counts = {:?}", counts);
}