Rust Reference ยท Smart Pointers and Memory
Rust Arc<T> type
Reference for Rust Arc<T>: thread-safe shared ownership with atomic counts, Arc::clone, Arc<Mutex<T>>, make_mut, try_unwrap and the Send/Sync rules.
Arc<T> is the thread-safe sibling of Rc<T>: an "atomically reference counted" pointer. Cloning it increments the strong count with an atomic operation, so any number of threads can own the same heap value, and the value is dropped when the last owner goes away.
Arc<T> gives shared, read-only access. For mutation, wrap the data in a lock: Arc<Mutex<T>> or Arc<RwLock<T>>, or use atomics. Arc<T> is Send and Sync only when T is both Send and Sync, which is why Arc<RefCell<T>> does not compile across threads.
use std::sync::Arc; let data = Arc::new(vec![1, 2, 3]); let for_thread = Arc::clone(&data);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub struct Arc<T: ?Sized, A: Allocator = Global> { /* private */ } impl<T> Arc<T> { pub fn new(data: T) -> Arc<T>; pub fn new_cyclic<F>(data_fn: F) -> Arc<T> where F: FnOnce(&Weak<T>) -> T; pub fn try_unwrap(this: Arc<T>) -> Result<T, Arc<T>>; pub fn into_inner(this: Arc<T>) -> Option<T>; } impl<T: ?Sized> Arc<T> { pub fn strong_count(this: &Arc<T>) -> usize; pub fn weak_count(this: &Arc<T>) -> usize; pub fn downgrade(this: &Arc<T>) -> Weak<T>; pub fn get_mut(this: &mut Arc<T>) -> Option<&mut T>; pub fn ptr_eq(this: &Arc<T>, other: &Arc<T>) -> bool; } impl<T: Clone> Arc<T> { pub fn make_mut(this: &mut Arc<T>) -> &mut T; }
| Function | Description |
|---|---|
Arc::new(v) |
Allocates v with strong count 1. |
Arc::clone(&a) |
New owner; atomic increment. |
Arc::strong_count / weak_count |
Counts at that instant; may be stale under concurrency. |
Arc::downgrade |
Creates a sync::Weak<T>. |
Arc::get_mut |
&mut T only if the Arc is unique (no other strong or weak pointers). |
Arc::make_mut |
&mut T, cloning the value if it is shared (copy-on-write). |
Arc::try_unwrap / into_inner |
Take the value out of a unique Arc. into_inner returns None for the non-last owner and is race-free when several threads race to unwrap. |
Edge cases. The counts are snapshots: another thread can change them right after you read. Use try_unwrap or get_mut (which check atomically) rather than strong_count() == 1 followed by an action. Cycles of Arc leak just as cycles of Rc do.
Usage notes
- Use
Arc<T>only when threads (orasynctasks that may move between threads) need shared ownership; otherwiseRc<T>is cheaper. - Cloning is an atomic read-modify-write: fast but not free, so clone once per task, not once per loop iteration.
Arc<Mutex<T>>is the standard pattern for shared mutable state; for read-heavy data considerArc<RwLock<T>>, or swap wholeArc<T>snapshots.Arc<str>andArc<[T]>give cheaply shareable immutable text and slices.thread::scopelets threads borrow data directly, so noArcis needed when threads cannot outlive the caller.- A poisoned mutex inside an
ArcreturnsErrfromlock()after a panic in another thread.
Related
- Rc, Weak, Cell
- Tutorial: Rc and Arc, Mutex and RwLock, Send and Sync