Add first version of part 14
[rust-101.git] / workspace / src / part14.rs
1 // Rust-101, Part 14: Mutex, Sync (WIP)
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 should not be surprising.
14     pub fn new(val: usize) -> Self {
15         ConcurrentCounter(Arc::new(Mutex::new(val)))
16     }
17
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;
22     }
23
24     pub fn get(&self) -> usize {
25         let counter = self.0.lock().unwrap();
26         *counter
27     }
28 }
29
30 // Now our counter is ready for action.
31 pub fn main() {
32     let counter = ConcurrentCounter::new(0);
33
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 || {
37         for _ in 0..10 {
38             thread::sleep_ms(15);
39             counter1.increment(2);
40         }
41     });
42
43     // The second thread increments the counter by 3 every 20ms.
44     let counter2 = counter.clone();
45     let handle2 = thread::spawn(move || {
46         for _ in 0..10 {
47             thread::sleep_ms(20);
48             counter2.increment(3);
49         }
50     });
51
52     // Now we want to watch the threads working on the counter.
53     for _ in 0..50 {
54         thread::sleep_ms(5);
55         println!("Current value: {}", counter.get());
56     }
57
58     // Finally, 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());
62 }
63
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.
68
69