Answer#
Most Rust code needs none of these: values live in variables and are lent with &. They solve specific problems:
| Type | Owners | Threads | Use it for |
|---|---|---|---|
Box<T> | one | any | a value on the heap; recursive types; Box<dyn Trait> |
Rc<T> | many | one only | shared read-only data in a single-threaded program |
Arc<T> | many | many | the same, when threads are involved |
Mutex<T> | many | letting one thread at a time change the value | |
RefCell<T> | one only | changing a value that is shared through an Rc |
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Box: one owner, value on the heap.
let boxed = Box::new(5);
println!("box: {}", *boxed + 1);
// Rc: several owners in one thread (counted, not thread-safe).
let shared = Rc::new(String::from("shared text"));
let other = Rc::clone(&shared);
println!("rc: {} owners, {}", Rc::strong_count(&shared), other);
// Arc + Mutex: several owners across threads, one writer at a time.
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..4)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
*counter.lock().unwrap() += 1;
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("arc: {}", *counter.lock().unwrap());
}box: 6
rc: 2 owners, shared text
arc: 4Why it works#
Rc and Arc keep a count of owners and free the value when the count reaches zero. Rc counts without synchronization, so it is faster, and the compiler refuses to send it to another thread. Arc uses atomic operations, so it can cross threads. A shared value is read-only unless it sits inside a Mutex, because two threads changing the same data at once would be a data race.
Common mistakes#
- Using
Arc<Mutex<T>>by reflex. Often a channel (std::sync::mpsc) or giving each thread its own part of the data is simpler. - Holding a
MutexGuardacross a long operation. The lock is released when the guard goes out of scope, so keep that scope small. - Building reference cycles with
Rc, which are never freed. UseWeakfor the back-pointer.
Related questions#
Does Rust have a garbage collector?#
No: memory is freed when the owner goes out of scope, and Rc and Arc free theirs when the last owner goes.