1 // Rust-101, Part 14: Mutex, Interior Mutability, 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 pub fn increment(&self, by: usize) {
19 // `lock` on a mutex returns a *guard*, giving access to the data contained in the mutex.
20 let mut counter = self.0.lock().unwrap();
21 *counter = *counter + by;
24 // The function `get` returns the current value of the counter.
25 pub fn get(&self) -> usize {
30 // Now our counter is ready for action.
32 let counter = ConcurrentCounter::new(0);
34 // We clone the counter for the first thread, which increments it by 2 every 15ms.
35 let counter1 = counter.clone();
36 let handle1 = thread::spawn(move || {
39 counter1.increment(2);
43 // The second thread increments the counter by 3 every 20ms.
44 let counter2 = counter.clone();
45 let handle2 = thread::spawn(move || {
48 counter2.increment(3);
52 // Now we watch the threads working on the counter.
55 println!("Current value: {}", counter.get());
58 // Finally, we wait for all the threads to finish to be sure we can catch the counter's final value.
59 handle1.join().unwrap();
60 handle2.join().unwrap();
61 println!("Final value: {}", counter.get());
64 // **Exercise 14.1**: Besides `Mutex`, there's also [`RwLock`](http://doc.rust-lang.org/stable/std/sync/struct.RwLock.html), which
65 // provides two ways of locking: One that grants only read-only access, to any number of concurrent readers, and another one
66 // for exclusive write access. (Notice that this is the same pattern we already saw with shared vs. mutable borrows.) Change
67 // the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.
69 // **Exercise 14.2**: Add an operation `compare_and_inc(&self, test: usize, by: usize)` that increments the counter by
70 // `by` *only if* the current value is `test`.