Arc
Arc<T> allows shared read-only access via Arc::clone:
use std::sync::Arc; use std::thread; fn main() { let v = Arc::new(vec![10, 20, 30]); let handles = (0..5).map(|_| { let v = Arc::clone(&v); thread::spawn(move || { let thread_id = thread::current().id(); println!("{thread_id:?}: {v:?}"); }) }).collect::<Vec<_>>(); for handle in handles { handle.join().unwrap(); } println!("v: {v:?}"); }
Arcstands for “Atomic Reference Counted”, a thread safe version ofRcthat uses atomic operations.Arc<T>implementsClonewhether or notTdoes. It implementsSendandSyncif and only ifTimplements them both.Arc::clone()has the cost of atomic operations that get executed, but after that the use of theTis free.- Beware of reference cycles,
Arcdoes not use a garbage collector to detect them.std::sync::Weakcan help.