re-do deepaksirone's fix on the actual source file
[rust-101.git] / workspace / src / part15.rs
1 // Rust-101, Part 15: Mutex, Interior Mutability (cont.), RwLock, Sync
2 // ===================================================================
3
4 use std::sync::{Arc, Mutex};
5 use std::thread;
6 use std::time::Duration;
7
8
9 // The derived `Clone` implementation will clone the `Arc`, so all clones will actually talk about the same counter.
10 #[derive(Clone)]
11 struct ConcurrentCounter(Arc<Mutex<usize>>);
12
13 impl ConcurrentCounter {
14     // The constructor just wraps the constructors of `Arc` and `Mutex`.
15     pub fn new(val: usize) -> Self {
16         unimplemented!()
17     }
18
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;
24     }
25
26     // The function `get` returns the current value of the counter.
27     pub fn get(&self) -> usize {
28         unimplemented!()
29     }
30 }
31
32 // Now our counter is ready for action.
33 pub fn main() {
34     let counter = ConcurrentCounter::new(0);
35
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 || {
39         for _ in 0..10 {
40             thread::sleep(Duration::from_millis(15));
41             counter1.increment(2);
42         }
43     });
44
45     // The second thread increments the counter by 3 every 20ms.
46     let counter2 = counter.clone();
47     let handle2 = thread::spawn(move || {
48         for _ in 0..10 {
49             thread::sleep(Duration::from_millis(20));
50             counter2.increment(3);
51         }
52     });
53
54     // Now we watch the threads working on the counter.
55     for _ in 0..50 {
56         thread::sleep(Duration::from_millis(5));
57         println!("Current value: {}", counter.get());
58     }
59
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());
64 }
65
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`.
68 // 
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.
71
72
73 // **Exercise 15.3**:  Change the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.
74
75