- Arc
- clone
Pass reference of read-only vector to thread improved
- In this solution the call to clone the Arc was moved inside the spawn.
examples/threads/pass-vector/src/main.rs
use std::sync::Arc; macro_rules! prt { ($text: expr, $var: expr) => { println!("{:11} {:?} {:p} {:?}", $text, $var, &$var, $var.as_ptr()); }; } fn main() { let animals = Arc::new(vec![ String::from("crab"), String::from("ant"), String::from("cat"), String::from("dog"), String::from("bat"), ]); prt!("Before:", animals); let mut handles = vec![]; for _ in 1..=3 { handles.push(std::thread::spawn({ let animals = animals.clone(); move || { list_animals(&animals); } })); } prt!("Started:", animals); for handle in handles { handle.join().unwrap(); } prt!("After:", animals); } fn list_animals(animals: &Vec<String>) { prt!(format!("{:?}", std::thread::current().id()), animals); //for animal in animals { // println!("{}", animal); //} }
Before: ["crab", "ant", "cat", "dog", "bat"] 0x7fff3f32bef8 0x5adca2be2480 Started: ["crab", "ant", "cat", "dog", "bat"] 0x7fff3f32bef8 0x5adca2be2480 ThreadId(2) ["crab", "ant", "cat", "dog", "bat"] 0x793310bff678 0x5adca2be2480 ThreadId(4) ["crab", "ant", "cat", "dog", "bat"] 0x7933103ff678 0x5adca2be2480 ThreadId(3) ["crab", "ant", "cat", "dog", "bat"] 0x7933107ff678 0x5adca2be2480 After: ["crab", "ant", "cat", "dog", "bat"] 0x7fff3f32bef8 0x5adca2be2480