I'm novice to Rust (v1.0.0) and thread-programming. I try to calculate elements of b-array using a-array. Each element of the b-array can be calculated independently of the others (parallel).
extern crate rand;
use rand::Rng;
use std::io;
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let mut a : [u32; 10] = [0; 10];
let mut b = Arc::new(Mutex::new([0; 10]));
let mut rng = rand::thread_rng();
for x in 0..9 {
a[x] = (rng.gen::<u32>() % 1000) + 1;
};
for x in 0..4 {
let b = b.clone();
thread::spawn(move || { let mut b = b.lock().unwrap();
for y in 0..4 {
b[x] += a[y] * a[y*2+1];
b[x+5] += a[y+1] * a[y*2];
}
});
};
thread::sleep_ms(1000);
for x in 0..a.len() {
println!("a({0})={1}, b({0})={2}", x, a[x], b[x]);
};
}
Can you help me:
- if I use:
let mut b = Arc::new(Mutex::new([u32; 10] = [0; 10]));
-> I get errorunresolved name 'u32'. Did you mean 'a'?
How can I set the type of array element ? - thread::sleep_ms(1000) - It is so rudely. How can I check that all thread is finished?
- How can I get back my calculated b[i] and/or gather thread-calculated b-arrays in the final one ? Now I've got error:
cannot index a value of type 'alloc::arc::Arc<std::sync::mutex::Mutex<[u32; 10]>>'
- Can I use only one b-array in memory and send into thread (using pointers) to calculating two elements of b-array?
Thank for solutions. Working code is (I've modified it for show problem):
extern crate rand;
use rand::Rng;
use std::thread;
use std::sync::{Arc, Mutex};
fn main() {
let mut a : [u32; 10000] = [0; 10000];
let b = Arc::new(Mutex::new([0u32; 10]));
let mut rng = rand::thread_rng();
for x in 0..10000 {
a[x] = (rng.gen::<u32>() % 10) + 1;
};
for x in 0..5 {
let b = b.clone();
thread::spawn(move || { let mut b = b.lock().unwrap();
println!("thread {} started", x);
for y in 0..5000 {
b[x] += a[y] * a[y*2+1];
b[x+5] += a[y+1] * a[y*2];
};
b[x] += a[x];
b[x+5] -= a[x];
println!("thread {} finished", x);
});
};
thread::sleep_ms(1000);
for x in 0..10 {
println!("b({0})={1}", x, b.lock().unwrap()[x]);
};
}
The output is:
thread 1 started
thread 1 finished
thread 3 started
thread 3 finished
thread 0 started
thread 0 finished
thread 2 started
thread 2 finished
thread 4 started
thread 4 finished
b(0)=149482
...
b(9)=149065
Threads are processed step-by-step.