Sub topic 3
Arc: shared ownership across threads
This chapter assumes you know Rust ownership, borrowing and lifetimes, closures with move, and thread::spawn with JoinHandle. You should also be comfortable with Result and unwrap. Here you will learn what Arc<T> is, how it behaves at runtime, and what it does not give you. It does not let you mutate the data. That is the job of Mutex, which comes later.
The problem Arc solves
thread::spawn takes a closure that must be 'static. The closure cannot borrow from the spawning function's stack, because the new thread might outlive that stack frame. Two obvious workarounds fail:
- Borrowing a local.
thread::spawn(|| println!("{}", data.len()))is rejected because the closure may outlivedata. - Moving the value.
movetransfers ownership into one closure. After that, no other thread can use the value.
Cloning the data gives each thread its own copy. That works for small values. It is wrong when the threads must see the same value, and it is wasteful for large data.
What you need is a value with several owners, where the data is freed when the last owner is gone. Rc<T> does this on a single thread. Arc<T>, the atomically reference-counted pointer, does it across threads.
How Arc works
Arc::new(value) allocates one block on the heap. The block holds the value and two counters, a strong count and a weak count. The Arc you hold is a pointer to that block.
Arc::clone(&a)increments the strong count and returns a new pointer to the same block. It does not copy the value.- Dropping an
Arcdecrements the strong count. - When the strong count reaches zero, the value is dropped and its destructor runs. The block itself is freed once the weak count also reaches zero.
The counter updates are atomic operations. Two threads can clone or drop handles at the same time without corrupting the count. That is what the "A" in Arc means, and it is the only difference in behavior from Rc.
You can watch the count change with Arc::strong_count:
use std::sync::Arc;
fn main() {
let a = Arc::new(String::from("shared"));
println!("count = {}", Arc::strong_count(&a)); // 1
let b = Arc::clone(&a);
println!("count = {}", Arc::strong_count(&a)); // 2
println!("same block: {}", Arc::ptr_eq(&a, &b)); // true
{
let _c = Arc::clone(&a);
println!("count = {}", Arc::strong_count(&a)); // 3
} // _c dropped here
println!("count = {}", Arc::strong_count(&a)); // 2
drop(b);
println!("count = {}", Arc::strong_count(&a)); // 1
}Sharing read-only data across threads
The usual pattern is to clone the Arc once per thread, before the spawn, and move the clone into the closure. Giving the clone the same name as the original shadows it, so each closure captures its own handle.
use std::sync::Arc;
use std::thread;
fn main() {
let words = Arc::new(vec![
String::from("alpha"),
String::from("beta"),
String::from("gamma"),
]);
let mut handles = Vec::new();
for id in 0..3 {
let words = Arc::clone(&words);
handles.push(thread::spawn(move || {
println!("thread {id} sees {} words, first is {}", words.len(), words[0]);
words[id].len()
}));
}
let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
println!("total letters: {total}");
println!("strong count after join: {}", Arc::strong_count(&words));
}The three "thread ..." lines can appear in any order. The last two lines are always total letters: 14 and strong count after join: 1. Each thread's closure is consumed when the thread finishes, which drops that thread's handle.
Why clone before the spawn
The clone has to happen on the spawning thread, outside the closure. If you wrote move || { let w = Arc::clone(&words); ... }, the closure would capture the original words and move it away. Only one thread could do that. Cloning first gives every thread an owned handle.
Arc::clone versus .clone()
a.clone() and Arc::clone(&a) do the same thing. The Rust community prefers the second form because it makes clear that only a pointer is copied. A reader scanning for expensive .clone() calls on large data will not be misled.
Arc is shared, not mutable
Arc<T> only hands out shared references (&T). That is what makes sharing safe: nobody can mutate the data while others read it. Trying to change the contents fails to compile:
use std::sync::Arc;
fn main() {
let n = Arc::new(5);
// Does not compile: cannot assign to data in an `Arc`.
*n += 1;
}There are three ways forward.
- Interior mutability. Put a
Mutex,RwLockor atomic inside theArc. This is the subject of the rest of the tutorial. - Unique access.
Arc::get_mut(&mut a)returnsSome(&mut T)only if the strong count is 1 (and there are noWeakpointers). Otherwise it returnsNone. - Copy on write.
Arc::make_mut(&mut a)gives&mut Twhen you are the only owner. If others exist, it clones the data into a fresh allocation first, so your handle becomes unique.
use std::sync::Arc;
fn main() {
let mut data = Arc::new(vec![1, 2, 3]);
let other = Arc::clone(&data);
// `data` is shared, so make_mut clones the Vec before mutating.
Arc::make_mut(&mut data).push(4);
println!("{:?} {:?}", data, other); // [1, 2, 3, 4] [1, 2, 3]
// Now `data` is the only owner, so we can take the value back out.
let owned: Vec<i32> = Arc::try_unwrap(data).unwrap();
println!("{:?}", owned);
}Arc::try_unwrap returns Err(arc) if other handles still exist. This is the standard way to get the value back after all worker threads have been joined.
Arc versus Rc
| Property | `Rc<T>` | `Arc<T>` |
|---|---|---|
| Reference count updates | Plain integer operations | Atomic operations |
| Can move to another thread | No, it is not `Send` | Yes, if `T: Send + Sync` |
| Cost of clone and drop | Very low | Slightly higher, because of atomic instructions |
| Typical use | Single-threaded shared ownership | Shared ownership across threads |
The compiler enforces the thread restriction through the Send and Sync marker traits, covered in the next chapter. For now, remember that Rc is rejected by thread::spawn and Arc is accepted. Do not use Arc in single-threaded code just in case. The atomic updates cost more than Rc's, and the type tells readers that threads are involved.
Edge cases and gotchas
Arc<T> is only Send when T allows it
Arc<T> is Send and Sync only if T is both Send and Sync. Arc<Rc<i32>> is not Send, and neither is Arc<RefCell<i32>>. Wrapping a thread-unsafe type in an Arc does not make it thread-safe. This is why Arc<Mutex<T>>, rather than Arc<RefCell<T>>, is the standard pairing.
strong_count is a snapshot
Another thread may clone or drop a handle right after you read the count. Use strong_count for debugging and tests, not for decisions such as "if the count is 1, I can mutate". Use get_mut or try_unwrap for that. They check and act as one operation.
Reference cycles leak
If two Arc values point to each other, each keeps the other's strong count above zero, and neither is ever freed. Rust does not detect cycles. For back-pointers, such as a child that refers to its parent, use Weak<T>. Call Arc::downgrade(&a) to get one. A Weak does not keep the value alive. Calling weak.upgrade() returns Some(Arc<T>) if the value still exists and None if it has been dropped.
The last owner runs the destructor
Whichever thread drops the last handle runs the value's Drop implementation. If that destructor is slow or blocks, it can stall an unexpected thread, such as a latency-sensitive worker. If this matters, send the final handle to a thread that is meant to do cleanup.
Cloning an Arc is not cloning the data
Arc<Vec<u8>> cloned 100 times still holds one Vec. But (*a).clone() or a.as_ref().clone() does copy the data. That is a common mistake when you meant to share.
Summary of the model
Arc<T>gives several owners one heap value. The value lives until the last owner is dropped.- Clone before spawning, and move one clone into each closure.
Arcgives read-only access. Mutation needs interior mutability, or unique ownership viaget_mut,make_mutortry_unwrap.- It costs atomic counter updates, so use
Rcwhen no threads are involved. - Cycles of
Arcleak. Break them withWeak.
Exercise
The code below tries to share a Vec<i32> between two threads and fails to compile. Explain why, then fix it so both threads print the length.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let a = thread::spawn(move || println!("{}", data.len()));
let b = thread::spawn(move || println!("{}", data.len()));
a.join().unwrap();
b.join().unwrap();
}
Show answer
The first move closure takes ownership of data, so the second closure would use a moved value. Wrap the vector in an Arc and give each closure its own clone: let data = Arc::new(vec![1, 2, 3]); let d1 = Arc::clone(&data); let d2 = Arc::clone(&data);, then move d1 into the first closure and d2 into the second. Add use std::sync::Arc;. Both threads then read the same vector, and it is freed after the last handle is dropped.
Exercise
After let mut a = Arc::new(vec![1]); let b = Arc::clone(&a);, what does Arc::get_mut(&mut a) return, and what happens if you call Arc::make_mut(&mut a).push(2) instead? What is b afterwards?
Show answer
Arc::get_mut returns None, because the strong count is 2. Arc::make_mut clones the vector into a new allocation, so a becomes unique and the push succeeds, giving [1, 2]. b still points to the original block and holds [1].