Created
April 19, 2017 18:41
-
-
Save anonymous/2b6d5270db9125540decff7292a0f729 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::sync::{Arc, Mutex, Condvar}; | |
| use std::time::{Duration, Instant}; | |
| use std::thread; | |
| //use std::sync::atomic::{AtomicBool, Ordering}; | |
| trait Factory<'a> { | |
| type Output: 'a; | |
| fn create(&self) -> Self::Output; | |
| } | |
| struct ExpireStore<T> { | |
| value: Arc<T>, | |
| timestamp: Instant, | |
| recreate: bool, | |
| } | |
| struct Expire<T> { | |
| store: Mutex<ExpireStore<T>>, | |
| recreate: Condvar, | |
| lifetime: Duration, | |
| } | |
| impl<'a, T: 'a + Send + Sync> Expire<T> { | |
| fn new<F: Factory<'a, Output=T>>(factory: F, lifetime: Duration) -> Arc<Expire<T>> { | |
| let inital = factory.create(); | |
| let store = ExpireStore { | |
| value: Arc::new(inital), | |
| timestamp: Instant::now(), | |
| recreate: false, | |
| }; | |
| let exp = Arc::new(Expire { | |
| store: Mutex::new(store), | |
| recreate: Condvar::new(), | |
| lifetime: lifetime, | |
| }); | |
| let e = exp.clone(); | |
| thread::spawn(move || { | |
| while Arc::strong_count(&e) > 1 || Arc::weak_count(&e) > 0 { | |
| let store = e.store.lock().unwrap(); | |
| } | |
| }); | |
| exp | |
| } | |
| fn get(&self) -> Arc<T> { | |
| let mut store = self.store.lock().unwrap(); | |
| if store.timestamp.elapsed() >= self.lifetime { | |
| store.recreate = true; | |
| self.recreate.notify_one(); | |
| } | |
| store.value.clone() | |
| } | |
| } | |
| fn main() { | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment