How can this error be avoided?
There's another reference counted type with an incredibly cool name: Atomic RC. Atomicity, in this case, refers to non-divisible actions and/or containers, which means that they are thread-safe. Also, we'll need to pair the Arc type with a Mutex to allow us to lock the data for access. Here's the full code for a threaded implementation:
// 05/threads-2/src/main.rs
use std::thread; use std::sync::{Arc, Mutex}; struct MyCounter { count: i32 } fn wont_work() { let counter = Arc::new(Mutex::new(MyCounter {count: 0})); let another_counter = counter.clone(); thread::spawn(move || // new thread { let mut counter = another_counter.lock().expect("Locking of cloned counter failed"); counter.count += 1; }); println!("{}", counter.lock().unwrap().count); }
Usually, this code will print 0 because the print method tends to be reached before the mutation in the thread takes place.