1 use std::sync::{Arc, RwLock};
5 struct ConcurrentCounter(Arc<RwLock<usize>>);
7 impl ConcurrentCounter {
8 // The constructor should not be surprising.
9 pub fn new(val: usize) -> Self {
10 ConcurrentCounter(Arc::new(RwLock::new(val)))
13 pub fn increment(&self, by: usize) {
14 let mut counter = self.0.write().unwrap();
15 *counter = *counter + by;
18 pub fn get(&self) -> usize {
19 let counter = self.0.read().unwrap();
24 // Now our counter is ready for action.
26 let counter = ConcurrentCounter::new(0);
28 // We clone the counter for the first thread, which increments it by 2 every 15ms.
29 let counter1 = counter.clone();
30 let handle1 = thread::spawn(move || {
33 counter1.increment(2);
37 // The second thread increments the counter by 3 every 20ms.
38 let counter2 = counter.clone();
39 let handle2 = thread::spawn(move || {
42 counter2.increment(3);
46 // Now we want to watch the threads working on the counter.
49 println!("Current value: {}", counter.get());
52 // Finally, wait for all the threads to finish to be sure we can catch the counter's final value.
53 handle1.join().unwrap();
54 handle2.join().unwrap();
55 println!("Final value: {}", counter.get());