Hello.
So I am new to rust and trying to do some multithread programming in Rust.
With this piece of code:
use std::thread;
fn mod_prt(mut v: Vec<i32>) -> Vec<i32>{
v.push(2);
println!("Inside thread: {:?} ", v);
return v;
}
fn main() {
let mut v:Vec<i32> = Vec::new();
v.push(1);
v.push(3);
v.push(4);
println!("Outside thread: {:?} ", v);
}
Everything works as intended and the output is:
Inside thread: 1 2
Outside thread: 1 2 3 4
However, I am trying to get the function to works in a separate thread, and this main function definitely would not work:
fn main() {
let mut v:Vec<i32> = Vec::new();
v.push(1);
let handle = thread::spawn(move || {
v=mod_prt(v);
});
handle.join().unwrap();
v.push(3);
v.push(4);
println!("Outside thread: {:?} ", v);
}
I got the error:
borrow of moved value: `v`
Same thing happens when I tried to use passing by reference.
This code works fine for what it is:
use std::thread;
fn mod_prt(v: &mut Vec<i32>){
v.push(2);
println!("Inside thread: {:?} ", *v);
}
fn main() {
let mut v:Vec<i32> = Vec::new();
v.push(1);
mod_prt(&mut v);
v.push(3);
v.push(4);
println!("Outside thread: {:?} ", v);
}
However, this is a no-go:
fn main() {
let mut v:Vec<i32> = Vec::new();
v.push(1);
let handle = thread::spawn(move || {
mod_prt(&mut v);
});
handle.join().unwrap();
v.push(3);
v.push(4);
println!("Outside thread: {:?} ", v);
}
So yeah. I am definitely missing something.
What is the most easy way to pass a vector (value and reference) to a function, but execute it on a separated thread?
Thank you.
And also, in Rust, does multithreading means multiprocessing? Because it does not work like so in Python, a.k.a even if the program spans multithread, all threads will still be executed by a single processor, which is a bit useless imo.