Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block until one of two Receivers has available data?

Tags:

rust

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?

like image 254
deadfoxygrandpa Avatar asked Mar 16 '23 00:03

deadfoxygrandpa


1 Answers

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

like image 147
Manishearth Avatar answered Apr 22 '23 07:04

Manishearth