Skip to content

Instantly share code, notes, and snippets.

@stepancheg
Created June 21, 2017 00:37
Show Gist options
  • Save stepancheg/7af651d41b0a7ab97d21e47712025028 to your computer and use it in GitHub Desktop.
Save stepancheg/7af651d41b0a7ab97d21e47712025028 to your computer and use it in GitHub Desktop.
struct CyclicBarrierShared {
count: u32,
mutex: Mutex<(u32, bool)>,
condv: Condvar,
}
struct CyclicBarrier {
shared: Arc<CyclicBarrierShared>,
}
impl CyclicBarrier {
fn new(count: u32) -> Vec<CyclicBarrier> {
let shared = Arc::new(CyclicBarrierShared {
count: count,
mutex: Mutex::new((0, false)),
condv: Condvar::new(),
});
(0..count).map(|_| CyclicBarrier { shared: shared.clone() }).collect()
}
fn wait(&self) {
let mut g = self.shared.mutex.lock().expect("lock");
// going down
while g.1 {
g = self.shared.condv.wait(g).expect("wait");
}
if g.0 == self.shared.count - 1 {
g.1 = true;
self.shared.condv.notify_all();
return;
}
g.0 += 1;
while !g.1 {
g = self.shared.condv.wait(g).expect("wait");
}
if g.1 {
g.0 -= 1;
if g.0 == 0 {
g.1 = false;
self.shared.condv.notify_all();
}
return;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment