pulse/barrier.rs
1// Copyright 2015 Colin Sherratt
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::atomic::{AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex};
17
18use {Pulse, Signal, Waiting, Signals};
19
20pub struct Inner {
21 pub count: AtomicUsize,
22 pub trigger: Mutex<Option<Pulse>>,
23}
24
25/// A `Barrier` can listen for 1 or more `Signals`. It will only transition
26/// to a `Pulsed` state once all the `Signals` have `Pulsed`.
27pub struct Barrier {
28 inner: Arc<Inner>,
29}
30
31pub struct Handle(pub Arc<Inner>);
32
33impl Barrier {
34 /// Create a new Barrier from an Vector of `Siganl`s
35 pub fn new(pulses: &[Signal]) -> Barrier {
36 // count items
37 let inner = Arc::new(Inner {
38 count: AtomicUsize::new(pulses.len()),
39 trigger: Mutex::new(None),
40 });
41
42 for pulse in pulses {
43 pulse.clone().arm(Waiting::barrier(Handle(inner.clone())));
44 }
45
46 Barrier { inner: inner }
47 }
48}
49
50impl Signals for Barrier {
51 fn signal(&self) -> Signal {
52 let (p, t) = Signal::new();
53
54 let mut guard = self.inner.trigger.lock().unwrap();
55 if self.inner.count.load(Ordering::Relaxed) == 0 {
56 t.pulse();
57 } else {
58 *guard = Some(t);
59 }
60 p
61 }
62}