Skip to content
Theory · Threads · lesson 3 of 7

Channels

In the previous lesson a thread handed back its result through join, and only once it had finished all its work. What if a worker wants to pass finished parts along one at a time, without waiting for the end of the shift?

A workshop has a pneumatic tube for that: a pipe between benches. One worker puts a capsule into the tube at his desk, and another takes it out at the other end. Capsules arrive in the order they were sent. Such a pipe between threads is called a channel.

The picture is off in one respect. With a real pneumatic tube you can send a capsule and keep a copy. A value sent into a channel is moved: the sender no longer has it.

A channel and its two ends

Rust
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let msg = String::from("hello");
        tx.send(msg).unwrap();
    });
    let got = rx.recv().unwrap();
    println!("{got}"); // hello
}

Let's go through the example line by line:

  1. mpsc::channel() creates a channel and returns a tuple of its two ends. We split it right away into tx, the sender, and rx, the receiver.
  2. move moves tx into the new thread: now that thread can send.
  3. tx.send(msg) moves the string into the channel. The method returns a Result: it fails if the receiver is already gone.
  4. rx.recv() waits until a message shows up in the channel and returns a Result holding it.
  5. main prints hello.

There is no need for join here: recv itself waits until the thread sends the string.

The letters mpsc stand for "multiple producer, single consumer": a channel can have any number of senders but only one receiver.

Looping over the receiver

You can walk over the receiver with a for loop. Each step of the loop waits for the next message. This example has no use at all: a function's path can be written in full, std::sync::mpsc::channel() and std::thread::spawn. It means the same thing; use only shortens the code.

Rust
fn main() {
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        for word in ["one", "two", "three"] {
            tx.send(word).unwrap();
        }
    });
    let mut got = Vec::new();
    for word in rx {
        got.push(word);
    }
    println!("{got:?}"); // ["one", "two", "three"]
}

What happens here:

  1. The thread sends three words in order.
  2. for word in rx takes the messages in the order they were sent: the channel works as a queue.
  3. After sending the third word, the thread ends, and tx is dropped with it.
  4. The loop sees that no senders are left and ends.
  5. main prints ["one", "two", "three"].

The rule for the end of the loop is worth remembering: a for over a receiver ends when ALL senders have been dropped. While even one is alive, the loop waits for the next message.

Several senders

A sender can be cloned: tx.clone() gives one more entrance into the same tube. Each worker gets its own clone, and the messages from all of them arrive at one receiver.

Rust
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    for id in 1..=3 {
        let tx = tx.clone();
        std::thread::spawn(move || tx.send(id * 10).unwrap());
    }
    drop(tx);
    let mut total = 0;
    for n in rx {
        total += n;
    }
    println!("{total}"); // 60
}

Let's see what is new here:

  • on each step of the loop let tx = tx.clone(); shadows the name: the clone goes into the thread, and the original tx stays in main;
  • the operating system decides in which order 10, 20 and 30 arrive, so the example adds the numbers instead of printing them;
  • drop(tx) drops the original sender in main, and the loop ends when all three threads have finished.

Order is guaranteed only for the messages of one sender. Interviewers like to ask about this: "In what order do messages come out of a channel?"

Common mistake

The clones went to the threads, and the original sender stayed in main:

Rust
use std::sync::mpsc;

fn main() {
    let (tx, rx) = mpsc::channel();
    for id in 1..=3 {
        let tx = tx.clone();
        std::thread::spawn(move || tx.send(id * 10).unwrap());
    }
    let mut total = 0;
    for n in rx { // ✗
        total += n;
    }
    println!("{total}");
}

The program compiles, but it hangs and prints nothing. All three messages arrived and the threads ended, but the tx in main is still alive. The channel is open, and the loop waits forever for a fourth message. The fix is drop(tx) before the loop, as in the example above.

Key points

  • mpsc::channel() returns a pair (tx, rx); send moves a value into the channel, and recv waits for a message.
  • Messages from one sender arrive in the order they were sent.
  • for x in rx waits for each message and ends when every sender has been dropped; it needs no join.
  • tx.clone() gives one more sender; the original tx left in main keeps the channel open.