projects
/
rust-101.git
/ blobdiff
commit
grep
author
committer
pickaxe
?
search:
re
summary
|
shortlog
|
log
|
commit
|
commitdiff
|
tree
raw
|
inline
| side by side
Fix innter -> inner typo
[rust-101.git]
/
solutions
/
src
/
counter.rs
diff --git
a/solutions/src/counter.rs
b/solutions/src/counter.rs
index afea9d04654d5e85452f7233318b93c588645879..acf8293acf13aecd2acd5f32446cde12ca80a463 100644
(file)
--- a/
solutions/src/counter.rs
+++ b/
solutions/src/counter.rs
@@
-1,5
+1,6
@@
use std::sync::{Arc, RwLock};
use std::thread;
use std::sync::{Arc, RwLock};
use std::thread;
+use std::time::Duration;
#[derive(Clone)]
pub struct ConcurrentCounter(Arc<RwLock<usize>>);
#[derive(Clone)]
pub struct ConcurrentCounter(Arc<RwLock<usize>>);
@@
-11,19
+12,19
@@
impl ConcurrentCounter {
}
pub fn increment(&self, by: usize) {
}
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) {
*counter = *counter + by;
}
pub fn compare_and_inc(&self, test: usize, by: usize) {
- let mut counter = self.0.write().unwrap
(
);
+ let mut counter = self.0.write().unwrap
_or_else(|e| e.into_inner()
);
if *counter == test {
*counter += by;
}
}
pub fn get(&self) -> usize {
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
}
}
*counter
}
}
@@
-36,7
+37,7
@@
pub fn main() {
let counter1 = counter.clone();
let handle1 = thread::spawn(move || {
for _ in 0..10 {
let counter1 = counter.clone();
let handle1 = thread::spawn(move || {
for _ in 0..10 {
- thread::sleep
_ms(15
);
+ thread::sleep
(Duration::from_millis(15)
);
counter1.increment(2);
}
});
counter1.increment(2);
}
});
@@
-45,14
+46,14
@@
pub fn main() {
let counter2 = counter.clone();
let handle2 = thread::spawn(move || {
for _ in 0..10 {
let counter2 = counter.clone();
let handle2 = thread::spawn(move || {
for _ in 0..10 {
- thread::sleep
_ms(20
);
+ thread::sleep
(Duration::from_millis(20)
);
counter2.increment(3);
}
});
// Now we want to watch the threads working on the counter.
for _ in 0..50 {
counter2.increment(3);
}
});
// Now we want to watch the threads working on the counter.
for _ in 0..50 {
- thread::sleep
_ms(5
);
+ thread::sleep
(Duration::from_millis(5)
);
println!("Current value: {}", counter.get());
}
println!("Current value: {}", counter.get());
}