Arc

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

  1. use std::sync::Arc;
  2. use std::thread;
  3. fn main() {
  4.     let v = Arc::new(vec![10, 20, 30]);
  5.     let mut handles = Vec::new();
  6.     for _ in 0..5 {
  7.         let v = Arc::clone(&v);
  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. }

This slide should take about 5 minutes.

  • 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 if and only if 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.