Pass and return ownership
- An alternate way to handle this situation is to return the vector.
- This way we pass the ownership back to the caller.
- This would only work properly if the threads do not need the same variable at the same time.
- So either they run sequentially in which case we don't gain CPU or each thread needs a different variable.
examples/threads/pass-and-return-reference/src/main.rs
macro_rules! prt { ($text: expr, $var: expr) => { println!("{:11} {:?} {:p} {:?}", $text, $var, &$var, $var.as_ptr()); }; } fn main() { let animals = vec![ String::from("crab"), String::from("ant"), String::from("cat"), String::from("dog"), String::from("bat"), ]; prt!("Before:", animals); let handle = std::thread::spawn(move || { list_animals(&animals); animals }); // Here we cannot access animals //prt!("Started:", animals); println!("Started:"); let animals = handle.join().unwrap(); prt!("After:", animals); } fn list_animals(animals: &Vec<String>) { prt!(format!("{:?}", std::thread::current().id()), animals); }
Before: ["crab", "ant", "cat", "dog", "bat"] 0x7ffe2316f6f0 0x62aa56783480 Started: ThreadId(2) ["crab", "ant", "cat", "dog", "bat"] 0x730f1d3ff558 0x62aa56783480 After: ["crab", "ant", "cat", "dog", "bat"] 0x7ffe2316fb10 0x62aa56783480