split part 11 into two, and explain interior mutability and Cell and RefCell in the...
[rust-101.git] / solutions / src / counter.rs
index 265fb99d972fcfd6388c6445a207082e42c00320..afea9d04654d5e85452f7233318b93c588645879 100644 (file)
@@ -2,7 +2,7 @@ use std::sync::{Arc, RwLock};
 use std::thread;
 
 #[derive(Clone)]
-struct ConcurrentCounter(Arc<RwLock<usize>>);
+pub struct ConcurrentCounter(Arc<RwLock<usize>>);
 
 impl ConcurrentCounter {
     // The constructor should not be surprising.
@@ -15,6 +15,13 @@ impl ConcurrentCounter {
         *counter = *counter + by;
     }
 
+    pub fn compare_and_inc(&self, test: usize, by: usize) {
+        let mut counter = self.0.write().unwrap();
+        if *counter == test {
+            *counter += by;
+        }
+    }
+
     pub fn get(&self) -> usize {
         let counter = self.0.read().unwrap();
         *counter