Skip to content

Support channels with multiple receivers #25992

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jonhoo opened this issue Jun 3, 2015 · 4 comments
Closed

Support channels with multiple receivers #25992

jonhoo opened this issue Jun 3, 2015 · 4 comments

Comments

@jonhoo
Copy link
Contributor

jonhoo commented Jun 3, 2015

It would be useful if rust provided a channel that supported a single sender and multiple receivers. Specifically, a channel where any item sent on the channel is received by exactly one receiver (i.e. not broadcast).

One example of where this might be used is to have a worker pool for a TCP server:

use std::net;
use std::thread;
use std::sync::mpsc;

let listener = net::TcpListener::bind("127.0.0.1:80").unwrap();

fn handle_clients(streams: mpsc::Receiver<net::TcpStream>) {
    for s in streams.iter() {
      // handle s
    }
}

let (tx, rx) = mpsc::channel();
let pool = (1..10).map(|_| {
  let local_rx = rx.clone();
  thread::spawn(move || {
    handle_clients(local_rx);
  });
}).collect();

// accept connections and process them, spawning a new thread for each one
for stream in listener.incoming() {
    match stream {
        Ok(stream) => {
            tx.send(stream);
        }
        Err(e) => { /* connection failed */ }
    }
}

// close the socket server
drop(listener);

Since Receiver is not Sync nor Copy, this obviously doesn't currently work. There has been some discussion in #2158 on a similar topic, though the objections there seem to be about full-duplex channels rather than single-writer-multi-reader channels.

@jdm
Copy link
Contributor

jdm commented Jun 3, 2015

This is the same as storing Arc<Mutex<Receiver<T>>> wherever you want multiple receivers, right?

@jdm
Copy link
Contributor

jdm commented Jun 3, 2015

Oh, I guess that doesn't necessarily work fairly if you're using blocking receive, as whichever one grabs the lock first would win.

@alexcrichton
Copy link
Member

This is a dupe of rust-lang/rfcs#848, so closing in favor of that, but @jdm's suggestion is the current method to get a "multi-receiver" situation as well.

@marcusklaas
Copy link
Contributor

FYI, there is a crate which provides this functionality: https://github.com/mahkoh/comm/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants