Fix an Arc<RefCell<Vec<i32>>> the compiler refuses to share between threads
Three threads record their ids into one shared vector, and main prints the sorted result. The program does not compile: error[E0277]: `RefCell<Vec<i32>>` cannot be shared between threads safely. Explain why Arc alone does not make this work and fix the shared value.
Requirements:
- Keep the three
thread::spawncalls; each thread writes into the shared vector. - Do not return the ids through
joinand do not useunsafe. - The program prints
[0, 1, 2].
use std::cell::RefCell;
use std::sync::Arc;
use std::thread;
fn main() {
let hits = Arc::new(RefCell::new(Vec::new()));
let mut handles = Vec::new();
for id in 0..3 {
let hits = Arc::clone(&hits);
handles.push(thread::spawn(move || {
hits.borrow_mut().push(id);
}));
}
for h in handles {
h.join().unwrap();
}
let mut all = hits.borrow().clone();
all.sort();
println!("{all:?}");
}Find and fix the bug.
Arc hands each thread only &T, so the value inside must be Sync, and RefCell is not: its borrow counter is non-atomic. Replace it with Mutex and write through hits.lock().unwrap(); the program prints [0, 1, 2].
- Expecting
Arcto make its contents thread-safe, though it only shares them by&T - Believing
RefCellis banned from threads entirely, though it isSendand only lacksSync - Reaching for
unsafe impl Sync, which promises a safety the non-atomic borrow counter cannot keep
- When would an
AtomicUsizeinside theArcreplace theMutexhere? - Why may a
RefCellbe moved into one thread whole while it may not be shared?
Arc solves only ownership: each thread gets its own pointer to one value, but access through it is shared, &T. So for Arc<T> to be handed to a thread, T must be Sync. RefCell counts its borrows with plain, non-atomic operations: two threads calling borrow_mut at once could both see "free". That is why RefCell is not Sync, and the compiler stops the program before it runs.
The fix is an interior-mutability type that enforces turns itself: Mutex. lock() also takes &self, so it works through Arc:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let hits = Arc::new(Mutex::new(Vec::new()));
let mut handles = Vec::new();
for id in 0..3 {
let hits = Arc::clone(&hits);
handles.push(thread::spawn(move || {
hits.lock().unwrap().push(id);
}));
}
for h in handles {
h.join().unwrap();
}
let mut all = hits.lock().unwrap().clone();
all.sort();
println!("{all:?}"); // [0, 1, 2]
}The sort is there because the threads write in arbitrary order. If writes are rare and reads frequent, RwLock fits; for a single number, an atomic type such as AtomicUsize. Arc<Mutex<T>> is the multithreaded twin of Rc<RefCell<T>>: the same "shared owner + mutation through &self" pattern, but with an atomic count and a lock.