Back to questions
JuniorTheoryCommon
What does the program print?
use std::sync::{Arc, Mutex};
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let c = Arc::clone(&counter);
handles.push(std::thread::spawn(move || *c.lock().unwrap() += 1));
}
handles.into_iter().for_each(|h| h.join().unwrap());
println!("{}", counter.lock().unwrap());
}4
- Expecting
0because each thread got its own clone:Arc::cloneadds another owner of the sameMutex, so all four threads change one counter. - Expecting lost updates as in a data race: the thread holds the lock from
lock()until its guard drops, so the four increments happen one after another.
- What would the compiler say if you replaced
ArcwithRcin this program? - Why does the program print the total only after joining every handle?