Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 132 ยท Concurrency

Message Passing with Channels

Send data between Rust threads with std::sync::mpsc channels: send and recv, multiple producers, closing, try_recv, bounded sync_channel, and worker patterns.

There are two big ways to let threads cooperate: share memory and protect it with locks, or pass messages so that each piece of data belongs to one thread at a time. The second idea has a slogan borrowed from the Go language: do not communicate by sharing memory; share memory by communicating. Rust supports both styles. This lesson is about the message-passing one, which is often simpler to reason about because there is nothing to lock.

A channel is a one-way pipe with two ends: a sender (Sender<T>) and a receiver (Receiver<T>). One thread puts values in, another takes them out, in the order they were sent. Rust's ownership rules make channels especially natural: sending a value moves it, so the sender can no longer touch it. You will build on Threads here, and the next lesson, Mutex and RwLock, covers the shared-memory alternative.

The standard library channel is std::sync::mpsc: multiple producer, single consumer. Many senders (clone the Sender), one receiver.

A first channel

mpsc::channel() returns the two ends as a tuple. The sender is moved into a thread; the receiver stays here.

Rust Send a message to the main thread

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.

The names tx and rx (transmit, receive) are conventional. The channel's element type, String here, is inferred from the first send.

send returns a Result: it fails only if the receiver has already been dropped (nobody can ever read the value). recv returns a Result too: it fails only when the channel is empty and every sender has been dropped (no message can ever arrive). Both failures carry useful information, which we exploit below.

Sending moves the value

Because a send transfers ownership, the compiler stops you from using a value after you handed it over. This is how Rust prevents two threads from having the same data at once:

Rust Using a value after sending it (fails on purpose)

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.

TEXT
error[E0382]: borrow of moved value: `report`

The line println!("sent {report}") is the culprit: send took ownership of report. If you need the value after sending, clone it first (and consider whether you really need it, as the point of channels is a clean hand-off).

Receiving many messages

A thread can send many values. The receiver is an iterator: for message in rx blocks for each message and ends when all senders are gone.

Rust Iterating over a receiver

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.

With one producer, messages arrive in exactly the order they were sent (a channel is a FIFO queue). The loop ends because the producer's closure finished and dropped tx. This is the standard way to signal "no more data": drop all the senders.

A classic bug follows from that rule. If you keep a Sender alive somewhere, say in main, the for message in rx loop waits forever:

Rust
let (tx, rx) = mpsc::channel::<i32>();
let tx2 = tx.clone();
thread::spawn(move || { tx2.send(1).unwrap(); });
for m in rx { println!("{m}"); } // never ends: `tx` in main is still alive

The fix is drop(tx); in main once you have cloned all you need. Remember it, because it is the most common channel mistake.

Multiple producers

Clone the Sender to give each producer its own handle. All of them feed the same receiver.

Rust Several 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.

Within one producer, messages keep their order, but messages from different producers can interleave in any way. When you need stable output, collect and sort, or have each message carry an identifier so the receiver can put results back in order.

Non-blocking and timed receives

recv() blocks. Sometimes the receiver has other work to do, so there are variants:

Method Behavior
recv() Wait until a message or until disconnected.
try_recv() Return immediately: Ok(msg), Err(Empty) or Err(Disconnected).
recv_timeout(d) Wait up to a duration: Err(Timeout) or Err(Disconnected).
iter() / for Blocking iterator until disconnected.
try_iter() Yields messages already waiting, then stops without blocking.
Rust try_recv and recv_timeout

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.

The difference between Empty and Disconnected is important. Empty means "try again later"; Disconnected means "stop, it is over". A polling loop must handle both.

A message sent before the senders were dropped is still delivered: dropping a sender does not discard queued data. You always receive everything that was sent, then the disconnect.

What can you send?

Any type that is Send (see Threads). That includes numbers, String, Vec, your own structs and enums, and even closures and other channel ends. An enum of commands is a very common message type, because a thread can then handle several kinds of request with a single match:

Rust An enum as the message protocol

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.

The calculator thread owns its state (value); nobody else can touch it. All access goes through messages. This is the actor idea: a thread that owns data and serves requests, with no mutex needed. To get a reply, include a Sender inside the request, a "return address":

Rust Request and reply with a return address

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.

Bounded channels: sync_channel

mpsc::channel() is unbounded: send never blocks, so a fast producer and a slow consumer can fill your memory with queued messages. A sync_channel(capacity) has a fixed buffer: when it is full, send blocks until the receiver makes room. This is called backpressure, and it keeps a pipeline's memory use under control.

Rust Backpressure with sync_channel

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.

try_send is the non-blocking version; it returns the value in Full(value) so nothing is lost. With capacity 0, sync_channel(0) is a rendezvous channel: every send waits until a receiver is ready to take the value, so sender and receiver meet at each message.

Rust A slow consumer slows the producer down

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.

The producer can never get more than a few messages ahead. In an unbounded channel it would have finished instantly, leaving everything queued.

The worker pool pattern

A very common design: one queue of jobs, several workers pulling from it, one queue of results. The standard Receiver is single-consumer, so to share it among workers you wrap it in Arc<Mutex<...>> (you will meet Mutex properly in the next lesson); each worker locks the receiver just long enough to take one job.

Rust A small worker pool

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.

Study the shutdown sequence, because it is the whole trick: drop job_tx so each worker's recv() returns Err, then the workers exit and drop their result_tx clones, so the result channel closes and result_rx.iter() ends. Closing channels is the shutdown signal. No flags, no sleeping.

Index numbers travel with the jobs, so the results can be restored to input order even though the workers finished in a different order.

In real projects you will often use a ready-made channel from a crate: crossbeam-channel (multi-consumer, select!, usually faster) or std::sync::mpsc in simple cases. Since Rust 1.67 the standard channel is built on the crossbeam implementation internally, so its performance is much better than older articles suggest. For async code, tokio and other runtimes bring their own channels.

Channels or shared state?

Prefer channels when... Prefer a Mutex or atomics when...
Data flows one way through stages (pipelines) Many threads read and update one small value
A thread owns a resource and others make requests You need quick access to a shared cache or counter
You want clear ownership and easy shutdown Latency matters and messages would be too heavy
Work is distributed to workers The data is large and cannot be moved cheaply

Both are fine tools, and large programs mix them. The thing to avoid is sending references to shared state through a channel. Send ownership, or send an Arc.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does rx.recv() return Err?

    recv blocks while the channel is empty and a sender still exists. Once the queue is drained and all senders are gone, no message can ever arrive, so it returns Err(RecvError).
  2. 2. Why does for message in rx never finish when main keeps its original tx alive?

    The iterator ends only when the channel is disconnected. A forgotten sender keeps the channel open, so the loop waits forever. Call drop(tx) once all clones are made.
  3. 3. What happens to the value you send with tx.send(report)?

    send takes its argument by value. Ownership moves to the channel and then to the receiver; using the variable afterwards is compile error E0382.
  4. 4. What is the difference between channel() and sync_channel(n)?

    A bounded channel applies backpressure to fast producers. With capacity 0 each send waits for a receiver.
  5. 5. Messages from three producers arrive in the receiver. What is guaranteed?

    A channel is a FIFO queue per sender ordering, but scheduling decides how different senders' messages interleave, so sort or tag results when you need determinism.

Summary

  • mpsc::channel() gives a (Sender, Receiver) pair; send moves the value and recv blocks until a value arrives or all senders are gone.
  • Clone the Sender for multiple producers, and drop the original so the receiver's loop can end; the receiver is single-consumer.
  • Iterate with for msg in rx, poll with try_recv or try_iter, wait with a limit using recv_timeout.
  • Enums make good message protocols, and including a Sender in a request provides a reply address.
  • sync_channel(n) is bounded and applies backpressure; capacity 0 is a rendezvous.
  • A worker pool shares one receiver via Arc<Mutex<Receiver<T>>>; closing channels is the shutdown signal.
  • Order across different producers is not guaranteed, so tag and sort results when you need stable output.

Next: Shared State: Mutex and RwLock