Sub topic 3
Arc: shared ownership across threads
This chapter assumes you know Rust ownership and borrowing, closures with move, and thread::spawn with JoinHandle. It covers how Arc lets several threads own the same value. Locking and mutation come in later chapters.
The problem: move gives away ownership
A move closure takes ownership of every value it uses. That works for one thread. With several threads, the first one takes the value and none is left for the others.
use std::thread;
fn main() {
let data = vec![1, 2, 3];
let handle = thread::spawn(move || {
println!("{:?}", data);
});
// Does not compile: `data` was moved into the closure above.
// println!("{:?}", data);
handle.join().unwrap();
}A plain reference does not fix this. thread::spawn requires the closure to be 'static, meaning it cannot borrow from the spawning function's stack. The compiler cannot know the thread will finish before the borrowed value goes away.
Arc: a reference-counted pointer
Arc<T> stands for atomically reference-counted. It puts a value on the heap, together with a counter of how many Arc handles point to it. Each handle owns a share of the value. The value is dropped when the last handle is dropped.
You create a new handle with Arc::clone. This copies the pointer and adds one to the counter. It does not copy the data.
"Atomically" means the counter is updated with atomic CPU operations. Two threads can clone or drop handles at the same moment without corrupting the count.
A worked example
Each thread gets its own handle, and that handle is moved into the closure. The original stays in main.
use std::sync::Arc;
use std::thread;
fn main() {
let names = Arc::new(vec![String::from("ada"), String::from("grace")]);
let mut handles = Vec::new();
for id in 0..3 {
let names = Arc::clone(&names);
handles.push(thread::spawn(move || {
println!("thread {id} sees {} names", names.len());
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("strong count: {}", Arc::strong_count(&names));
}The three thread ... lines can appear in any order. The last line always prints strong count: 1, because each thread's handle is dropped when its closure finishes.
Inside the loop, let names = Arc::clone(&names); shadows the outer variable. The closure then moves the inner clone, so the outer Arc is untouched. This shadowing idiom is common in threaded Rust.
What Arc does not give you
Arc<T> hands out only shared references (&T) to its contents. Several owners can read, but nobody can mutate. This line fails to compile if added to the closure above:
// names.push(String::from("linus")); // error: cannot borrow data in an `Arc` as mutableThat restriction is what keeps the sharing safe. To change the value you need interior mutability that is safe across threads. The next chapters cover Mutex, which supplies it.
Common mistakes
- Cloning the data instead of the handle. Writing
(*names).clone()copies the wholeVec. Each thread then has its own private copy, and nothing is shared. - Moving the original
Arcinto a thread. If you skip the clone,mainloses its handle after the first spawn. - Using
Rcinstead.Rchas the same API but a non-atomic counter, and the compiler rejects it across threads. The next chapter explains why. - Expecting cycles to be freed. Two
Arcs that point at each other keep the counts above zero forever, so the values leak.Weakpointers break such cycles.
Exercise
Exercise
A program spawns 4 threads. Each one gets a handle from Arc::clone(&config), and main keeps the original. While all four threads are still running, what is Arc::strong_count(&config), and why does the compiler still refuse config.push(...) on an Arc<Vec<i32>>?
Show answer
The count is 5: one handle in main and one in each of the four threads. The push is refused because Arc<T> only gives shared (&T) access to the value. Mutating needs &mut, which would be unsafe with several owners. Safe mutation requires wrapping the value in something like a Mutex.