Arc<T> (Rust)
Arc<T> is an atomically reference-counted smart pointer for sharing ownership across threads. It is the thread-safe sibling of Rc, using atomic operations so the count is safe under concurrency.
Rust
When several threads need to own the same value, you wrap it in Arc<T> ('atomic reference counted'). Like Rc it tracks owners and drops the data when the last handle is gone, but it updates the count atomically so it is safe to clone and drop from multiple threads.
Arc only provides shared, immutable access. To mutate shared data across threads, pair it with a synchronization type: Arc<Mutex<T>> for exclusive locking, or Arc<RwLock<T>> for many-readers/one-writer. This Arc<Mutex<T>> pattern is the standard way to share mutable state between Rust threads.
Arc has slightly more overhead than Rc because of the atomic operations, so prefer Rc when you stay on one thread. The compiler will tell you when you need Arc — Rc isn't Send and won't cross a thread boundary.
Syntax
use std::sync::Arc;
let a = Arc::new(5);
let b = Arc::clone(&a); // move into another threadExamples
Rust
use std::sync::Arc;
use std::thread;
fn main() {
let data = Arc::new(vec![1, 2, 3]);
let d = Arc::clone(&data);
let h = thread::spawn(move || d.len());
println!("{}", h.join().unwrap());
}Output:
3