Loading
0xF0Lesson 16 of 17

Design a worker pipeline with channels

Coordinate producers and workers using message passing.

18 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use threads and channels to process jobs safely.

A common production pattern is queue-based processing: one part of the system produces work while workers consume tasks concurrently. Rust’s std::sync::mpsc and thread model make this safe and explicit.

main.rs
1use std::sync::mpsc;
2use std::thread;
3
4fn main() {
5    let (tx, rx) = mpsc::channel();
6    thread::spawn(move || {
7        for value in [3, 5, 7] {
8            tx.send(value).unwrap();
9        }
10    });
11
12    let mut sum = 0;
13    for item in rx {
14        sum += item;
15    }
16
17    println!("{}", sum);
18}
Output
15

Message passing avoids shared mutable state by default. As workloads grow, this pattern scales from small tools to service internals and background processors.

Try it

Up to 15 XP

Follow producer-consumer flow

Trace each stage in a channel-based worker pipeline.

Message 1 of 3Predicted 0/0
Producer thread
Channel queue
Worker loop

Key takeaways

  • Use threads and channels to process jobs safely.

  • Rust uses types and ownership rules to prevent common bugs.

  • Small experiments build intuition quickly.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Rust

These run for real. Write the program, press Run tests, and read what the compiler tells you - learning to read compiler messages is half of learning Rust.

Exercise 1

Aggregate queued job costs

+25 XP

Read one line of space-separated integers representing job costs. Send each cost through a channel from producer to consumer and print total cost.

  • Three jobs
  • Single job
main.rs
Loading editor…

Rust lessons are authored for modern stable Rust; exercises run on Rust 1.82 via Wandbox, a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…