1 // Rust-101, Part 15: Mutex, Interior Mutability (cont.), RwLock, Sync
2 // ===================================================================
4 use std::sync::{Arc, Mutex};
8 // The derived `Clone` implementation will clone the `Arc`, so all clones will actually talk about the same counter.
10 struct ConcurrentCounter(Arc<Mutex<usize>>);
12 impl ConcurrentCounter {
13 // The constructor just wraps the constructors of `Arc` and `Mutex`.
14 pub fn new(val: usize) -> Self {
18 // The core operation is, of course, `increment`.
19 pub fn increment(&self, by: usize) {
20 // `lock` on a mutex returns a guard, very much like `RefCell`. The guard gives access to the data contained in the mutex.
21 let mut counter = self.0.lock().unwrap();
22 *counter = *counter + by;
25 // The function `get` returns the current value of the counter.
26 pub fn get(&self) -> usize {
31 // Now our counter is ready for action.
33 let counter = ConcurrentCounter::new(0);
35 // We clone the counter for the first thread, which increments it by 2 every 15ms.
36 let counter1 = counter.clone();
37 let handle1 = thread::spawn(move || {
40 counter1.increment(2);
44 // The second thread increments the counter by 3 every 20ms.
45 let counter2 = counter.clone();
46 let handle2 = thread::spawn(move || {
49 counter2.increment(3);
53 // Now we watch the threads working on the counter.
56 println!("Current value: {}", counter.get());
59 // Finally, we wait for all the threads to finish to be sure we can catch the counter's final value.
60 handle1.join().unwrap();
61 handle2.join().unwrap();
62 println!("Final value: {}", counter.get());
65 // **Exercise 15.1**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by
66 // `by` *only if* the current value is `test`.
68 // **Exercise 15.2**: Rather than panicking in case the lock is poisoned, we can use `into_innter` on the error to recover
69 // the data inside the lock. Change the code above to do that. Try using `unwrap_or_else` for this job.
72 // **Exercise 15.3**: Change the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.