Created
June 21, 2017 00:37
-
-
Save stepancheg/7af651d41b0a7ab97d21e47712025028 to your computer and use it in GitHub Desktop.
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
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