How can I modify data by muti-threading


#1

Hi, guys, I’m just starting to use Rust recently, here is a question:
when I have a Vec data, and I want to modify each of it’s elements in a different thread, how can I achieve this?
for example:
struct ABC{

    a:String,
    b:i32,

}

fn main() {

let mut x1=ABC{a:"first".to_string(), b:1};
let mut x2=ABC{a:"second".to_string(), b:2};
let mut x3=ABC{a:"second".to_string(), b:3};
let all=vec![x1, x2, x3];

let mut ths=Vec::new();
let data=Arc::new(Mutex::new(all));
for i in 0usize..3 {
	let mut data=data.clone();
	let t=std::thread::spawn(move || {
		let mut p=data.lock().unwrap();
		p[i].b+=1;
		std::thread::sleep(std::time::Duration::new(5,0));
	});
	ths.push(t);
}

for i in ths {
	i.join().unwrap();
}

}

BUT, this comes to be just a blocked way, because each thread takes the ownership until data has been fully processed. So, how can I change to make it happen simultaneously?


#2

I suggest using rayon or jobsteal since they provide parallel iterators. I’ve compared some parallelization crates here: mandel-rust.

So your code would look s.th. like this (untested):

all.par_iter_mut()
         .for_each(|element| *element.b += 1);

#3

I’ll try them, thank you