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