Skip to content

Support channels with multiple receivers #25992

Closed
@jonhoo

Description

@jonhoo

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions