Skip to content

Instantly share code, notes, and snippets.

@henninglive
Forked from anonymous/playground.rs
Created April 19, 2017 18:41
Show Gist options
  • Select an option

  • Save henninglive/a183f47820e913f9ad02a909785c692e to your computer and use it in GitHub Desktop.

Select an option

Save henninglive/a183f47820e913f9ad02a909785c692e to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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