X-Git-Url: https://git.ralfj.de/rust-101.git/blobdiff_plain/ccf679adb3790903849f7d85b970b67582220952..126f7bfe68883e6465d42c529b00d797b2f8478a:/solutions/src/counter.rs diff --git a/solutions/src/counter.rs b/solutions/src/counter.rs index 265fb99..319058e 100644 --- a/solutions/src/counter.rs +++ b/solutions/src/counter.rs @@ -2,7 +2,7 @@ use std::sync::{Arc, RwLock}; use std::thread; #[derive(Clone)] -struct ConcurrentCounter(Arc>); +pub struct ConcurrentCounter(Arc>); impl ConcurrentCounter { // The constructor should not be surprising. @@ -11,12 +11,19 @@ impl ConcurrentCounter { } pub fn increment(&self, by: usize) { - let mut counter = self.0.write().unwrap(); + let mut counter = self.0.write().unwrap_or_else(|e| e.into_inner()); *counter = *counter + by; } + pub fn compare_and_inc(&self, test: usize, by: usize) { + let mut counter = self.0.write().unwrap_or_else(|e| e.into_inner()); + if *counter == test { + *counter += by; + } + } + pub fn get(&self) -> usize { - let counter = self.0.read().unwrap(); + let counter = self.0.read().unwrap_or_else(|e| e.into_inner()); *counter } }