1 // Rust-101, Part 14: Mutex, Sync (WIP)
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 should not be surprising.
14 pub fn new(val: usize) -> Self {
15 ConcurrentCounter(Arc::new(Mutex::new(val)))
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 pub fn get(&self) -> usize {
25 let counter = self.0.lock().unwrap();
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 want to watch the threads working on the counter.
55 println!("Current value: {}", counter.get());
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());
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.