Skip to content

Instantly share code, notes, and snippets.

@viperscape
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save viperscape/d938e1c16321bc5c8a3f to your computer and use it in GitHub Desktop.
Save viperscape/d938e1c16321bc5c8a3f to your computer and use it in GitHub Desktop.
latch and promise sync primitives
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