Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Standard Library Modules

The std::sync::mpsc module

Reference for std::sync::mpsc: channel and sync_channel, Sender and Receiver, send, recv, try_recv, recv_timeout, iteration and disconnection errors.

std::sync::mpsc provides multi-producer, single-consumer channels: a way for threads to send values to each other instead of sharing memory. mpsc::channel() returns a (Sender<T>, Receiver<T>) pair. The sender can be cloned and moved into many threads; there is exactly one receiver, which cannot be cloned.

Values are moved through the channel, so ownership passes from the sending thread to the receiving one. A channel closes when all senders are dropped (the receiver sees the end) or when the receiver is dropped (sends fail). That closing behavior is what ends for value in receiver loops.

Rust
use std::sync::mpsc;

let (tx, rx) = mpsc::channel();
tx.send(5).unwrap();
assert_eq!(rx.recv().unwrap(), 5);

Try it

Rust Many producers, one consumer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust try_recv, timeouts and disconnection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub fn channel<T>() -> (Sender<T>, Receiver<T>)               // unbounded
pub fn sync_channel<T>(bound: usize) -> (SyncSender<T>, Receiver<T>)  // bounded
Method Returns Description
Sender::send(v) Result<(), SendError<T>> Never blocks (unbounded); fails if the receiver is gone, returning v.
SyncSender::send(v) Result<(), SendError<T>> Blocks while the buffer is full.
SyncSender::try_send(v) Result<(), TrySendError<T>> Full(v) or Disconnected(v) instead of blocking.
Receiver::recv() Result<T, RecvError> Block until a value arrives; Err when all senders are dropped and the queue is empty.
Receiver::try_recv() Result<T, TryRecvError> Empty or Disconnected.
Receiver::recv_timeout(d) Result<T, RecvTimeoutError> Timeout or Disconnected.
Receiver::iter(), try_iter(), into_iter() iterators Blocking iteration, non-blocking drain, owning iteration.
Sender::clone() Sender<T> Another producer for the same channel.

Errors and edge cases: sync_channel(0) is a rendezvous channel: send waits until a receiver takes the value. Messages sent before a disconnect can still be received. Receiver is Send but not Sync; to share one among threads, put it in a Mutex.

Usage notes

  • If a for x in rx loop never ends, a Sender is still alive, usually the original you forgot to drop after cloning it.
  • An unbounded channel can grow without limit if the consumer is slower than the producers; use sync_channel for back-pressure.
  • Messages from one sender arrive in the order sent; the interleaving between different senders is unspecified.
  • Send enums to represent several message kinds (including a Shutdown variant) rather than several channels.
  • T must be Send. Sending an Rc is a compile error.
  • For multiple consumers, multi-consumer channels from third-party crates exist; the standard library's mpsc is single-consumer by design.
  • Receiver::try_iter is handy in a loop that does other work and drains whatever has arrived.