I'm new to Rust and trying to set up a one-directional graph of nodes using Senders and Receivers from std::sync::mpsc. Right now I have it working when each node has exactly one parent and one child, like this:
fn run(mut self) {
    let parent = self.parent.unwrap();
    loop {
        match parent.recv() {
            Ok(input) => {
                self.value = (self.next_value)(input);
                match self.kid {
                    Some(ref k) => { k.send(self.value).unwrap(); },
                    None => {}
                }
            },
            Err(_) => {}
        }
    }
}
But what I really want to do is have two parent nodes, where the next_value function is evaluated and the child nodes notified whenever either parent node sends out another value. I can't just use the blocking recv() method twice, and using polling and a non-blocking try_recv() call would probably work, but it seems really inefficient.
Is there a better way to do this?
You want to use select!()
fn run(mut self) {
    // obtain parents
    loop {
        select! {
           resp = parent1.recv() => match resp {...}
           resp = parent2.recv() => match resp {...}
        }
    }
}
If you have a dynamic number of channels to receive on, use mpsc::Select
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With