Design a worker pipeline with channels
Coordinate producers and workers using message passing.
- 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.
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}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 XPFollow producer-consumer flow
Trace each stage in a channel-based worker pipeline.
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.
Aggregate queued job costs
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
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…