- Arc
- clone
Pass reference of read-only vector to thread
- Arc allows us to have reference counting.
- Here the clone only copies the reference and not the whole data structure.
examples/threads/pass-reference-to-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 { let animals = animals.clone(); handles.push(std::thread::spawn(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!("{:?} {}", std::thread::current().id(), animal); //} }
Before: ["crab", "ant", "cat", "dog", "bat"] 0x7ffc60e9fbf8 0x6225d6993480 Started: ["crab", "ant", "cat", "dog", "bat"] 0x7ffc60e9fbf8 0x6225d6993480 ThreadId(2) ["crab", "ant", "cat", "dog", "bat"] 0x75e378bff678 0x6225d6993480 ThreadId(3) ["crab", "ant", "cat", "dog", "bat"] 0x75e3787ff678 0x6225d6993480 ThreadId(4) ["crab", "ant", "cat", "dog", "bat"] 0x75e373dff678 0x6225d6993480 After: ["crab", "ant", "cat", "dog", "bat"] 0x7ffc60e9fbf8 0x6225d6993480