Arc

Arc allows shared read-only access via its clone method:

  1. use std::thread;
  2. use std::sync::Arc;
  3. fn main() {
  4. let v = Arc::new(vec![10, 20, 30]);
  5. let mut handles = Vec::new();
  6. for _ in 1..5 {
  7. let v = v.clone();
  8. handles.push(thread::spawn(move || {
  9. let thread_id = thread::current().id();
  10. println!("{thread_id:?}: {v:?}");
  11. }));
  12. }
  13. handles.into_iter().for_each(|h| h.join().unwrap());
  14. println!("v: {v:?}");
  15. }
  • Arc stands for “Atomic Reference Counted”, a thread safe version of Rc that uses atomic operations.
  • Arc<T> implements Clone whether or not T does. It implements Send and Sync iff T implements them both.
  • Arc::clone() has the cost of atomic operations that get executed, but after that the use of the T is free.
  • Beware of reference cycles, Arc does not use a garbage collector to detect them.
    • std::sync::Weak can help.