Created
July 24, 2014 11:10
-
-
Save brendanzab/64b22f322c6d2ca9fa32 to your computer and use it in GitHub Desktop.
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
/// Sends cloned values to multiple monitoring `Receiver`s. | |
pub struct Signal<T> { | |
txs: Vec<Sender<T>>, | |
} | |
impl<T: Send> Signal<T> { | |
/// Create a signal with no monitors connected. | |
pub fn new() -> Signal<T> { | |
Signal { txs: Vec::new() } | |
} | |
/// Create a new `Receiver` to monitor signals. | |
pub fn new_monitor(&mut self) -> Receiver<T> { | |
let (tx, rx) = channel(); | |
self.txs.push(tx); | |
rx | |
} | |
} | |
impl<T: Clone + Send> Signal<T> { | |
/// Sends a clone of signal `x` to each connected `Receiver`. | |
pub fn send(&mut self, x: T) { | |
let txs = mem::replace(&mut self.txs, Vec::new()); | |
// orphaned `Sender`s will be removed from `txs` | |
self.txs = txs.move_iter().filter(|tx| { | |
tx.send_opt(x.clone()).is_ok() | |
}).collect(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment