Last active
August 29, 2015 14:10
-
-
Save viperscape/d938e1c16321bc5c8a3f to your computer and use it in GitHub Desktop.
latch and promise sync primitives
This file contains 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::atomic::{AtomicBool,Ordering}; | |
use std::sync::{Arc, RWLock}; | |
struct Latch { | |
latch:Arc<AtomicBool>, | |
} | |
impl Latch { | |
fn new () -> Latch { | |
Latch {latch:Arc::new(AtomicBool::new(false))} | |
} | |
fn close (&self) -> bool { | |
if !self.latch.compare_and_swap(false,true,Ordering::SeqCst) {true} | |
else {false} | |
} | |
fn latched (&self) -> bool { | |
self.latch.load(Ordering::SeqCst) | |
} | |
fn clone (&self) -> Latch { | |
Latch {latch:self.latch.clone()} | |
} | |
} | |
struct Promise<T> { | |
data: Arc<RWLock<Option<T>>>, | |
latch: Latch, | |
} | |
impl<T: Sync+Send> Promise<T> { | |
fn new () -> Promise<T> { | |
Promise {data: Arc::new(RWLock::new(None)), latch: Latch::new()} | |
} | |
fn deliver (&self, d:T) -> bool { | |
if self.latch.close() { | |
let mut data = self.data.write(); | |
*data = Some(d); | |
data.cond.broadcast(); //wake up others | |
true | |
} | |
else {false} | |
} | |
fn apply (&self, f: |&T| -> T) -> T { | |
if !self.latch.latched() { | |
let vw = self.data.write(); | |
vw.cond.wait(); | |
vw.downgrade(); //do this? | |
} | |
let v = self.data.read(); | |
match *v { | |
Some(ref r) => f(r), | |
None => panic!("promise signaled, value not present!"), | |
} | |
} | |
fn clone (&self) -> Promise<T> { | |
Promise {data: self.data.clone(), | |
latch: self.latch.clone()} | |
} | |
fn kill (self) { //promise is moved | |
if !self.latch.latched() { | |
let mut data = self.data.write(); | |
*data = None; | |
data.cond.broadcast(); //wake up others | |
} | |
} | |
} | |
fn main () { | |
let p: Promise<int> = Promise::new(); | |
let p2 = p.clone(); | |
spawn(proc() { | |
p2.deliver(1); | |
p2.deliver(-5); | |
}); | |
let nv = p.apply(|x| { println!("oldval: {}",x); *x+1 }); // 1 | |
let ov = p.apply(|x| *x ); | |
println!("newval: {}, oldval: {}",nv, ov); // 2, 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment