Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ CONCURRENCY WITH A CONTRACT
BUILD NOTE 42 / 53

Send the work, not a shared mess.

Coordinate threads with explicit messages and closure.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

A channel transfers messages between a sender and a receiver. std::sync::mpsc provides multiple producers and one receiver; sending an owned value moves it. The receiving iterator ends when every sender is dropped, so keeping an unused sender alive can accidentally block shutdown. sync_channel adds bounded capacity and backpressure, while channel is unbounded. Choose capacity and overload behavior deliberately rather than letting a fast producer grow memory without limit.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/channels/src/main.rs
use std::{sync::mpsc, thread};
fn main() {
    let (tx, rx) = mpsc::sync_channel(2);
    let worker = thread::spawn(move || {
        for n in 1..=3 {
            tx.send(n).unwrap();
        }
    });
    let total: i32 = rx.iter().sum();
    worker.join().unwrap();
    println!("total={total}");
}
↳ EXPECTED OUTPUT
total=6
  1. 1

    The bounded channel can hold at most two waiting messages.

  2. 2

    The producer drops its sender when it returns.

  3. 3

    The receiver’s iterator finishes after queued messages drain and all senders are gone.

From the extracted rust-workbench folder
cargo run -p lesson_channels

03 Mind the boundary

04 Your next build

A SMALL MISSION

Send three strings from a worker and collect them in order on the receiving thread.

Reveal one possible solution +
solutions/channels/src/main.rs
use std::{sync::mpsc, thread};
fn main() {
    let (tx, rx) = mpsc::channel();
    let h = thread::spawn(move || {
        for s in ["plan", "build", "test"] {
            tx.send(s.to_owned()).unwrap();
        }
    });
    let result: Vec<_> = rx.iter().collect();
    h.join().unwrap();
    assert_eq!(result, ["plan", "build", "test"]);
}

05 Check your reasoning

QUICK SIGNAL CHECK

When does rx.iter() finish after the queue drains?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.