tweak parts 11-15 again
[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
7
8 // The derived `Clone` implementation will clone the `Arc`, so all clones will actually talk about the same counter.
9 #[derive(Clone)]
10 struct ConcurrentCounter(Arc<Mutex<usize>>);
11
12 impl ConcurrentCounter {
13     // The constructor just wraps the constructors of `Arc` and `Mutex`.
14     pub fn new(val: usize) -> Self {
15         unimplemented!()
16     }
17
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;
23     }
24
25     // The function `get` returns the current value of the counter.
26     pub fn get(&self) -> usize {
27         unimplemented!()
28     }
29 }
30
31 // Now our counter is ready for action.
32 pub fn main() {
33     let counter = ConcurrentCounter::new(0);
34
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 || {
38         for _ in 0..10 {
39             thread::sleep_ms(15);
40             counter1.increment(2);
41         }
42     });
43
44     // The second thread increments the counter by 3 every 20ms.
45     let counter2 = counter.clone();
46     let handle2 = thread::spawn(move || {
47         for _ in 0..10 {
48             thread::sleep_ms(20);
49             counter2.increment(3);
50         }
51     });
52
53     // Now we watch the threads working on the counter.
54     for _ in 0..50 {
55         thread::sleep_ms(5);
56         println!("Current value: {}", counter.get());
57     }
58
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());
63 }
64
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`.
67 // 
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.
70
71
72 // **Exercise 15.3**:  Change the code above to use `RwLock`, such that multiple calls to `get` can be executed at the same time.
73
74