The move keyword

Nevertheless, it gives a great explanation of something we can do. We have two options: share the binding between the threads or send it to the second one. Since we won't use it in the main thread, we can add the move keyword before the closure and send the vector to the new thread, since it's Send. Let's see how we can make it work:

use std::thread;

fn main() {
let my_vec = vec![10, 33, 54];

let handle = thread::Builder::new()
.name("my thread".to_owned())
.spawn(move || {
println!("This is my vector: {:?}", my_vec);
})
.expect("could not create the thread");

if handle.join().is_err() {
println!("Something bad happened :(");
}
}

This now compiles and shows the list of numbers in the console, perfect! But, what if we want to be able to see it in the main thread, too? Trying to print the vector after the spawning of the second thread won't work, since the variable has been moved to the new thread, and we already saw that if we don't move the vector we cannot use it inside the thread. What can we do?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.196.172