
Understand it
An mpsc channel moves values from many producers to one consumer, and the move is what makes it safe — once sent, the sender no longer owns the value. After every sender is dropped, the receiver drains queued messages and then its iterator ends, so no sentinel message is required.
A channel separates the producer of a value from its consumer. In a multi-producer, single-consumer channel, several senders can submit messages to one receiver. Sending an owned String moves it into the channel; the sender cannot keep changing the same object afterward. That ownership transfer is a simple way to avoid sharing mutable state. If the sender needs its own copy too, make that duplication explicit.
The receiver loop can continue until every sender handle is dropped. A cloned sender counts as another live producer, even when it never sends anything. Accidentally keeping one clone in the main thread can make a receiving loop wait forever, because the channel is still open. Track sender ownership on paper and drop unused handles deliberately. Also handle send failure: the receiver may already be gone, and the failed send can return the unsent value to the caller.
Try spawning two producers that each send a labeled message. Do not assume which message arrives first unless you add an ordering mechanism. The receiver should process both and then finish once all senders are gone. Next, leave a sender clone alive and observe why the loop does not terminate; remove it and rerun. Channels work well when a task can be expressed as a stream of owned messages. A mutex is more suitable when workers truly need coordinated access to one shared object. Choose the communication shape before choosing the primitive.
If the consumer is slower than producers, an unbounded channel can accumulate messages and memory. A bounded channel gives backpressure: senders wait or receive an error when capacity is exhausted. Choose a capacity by measuring the burst you can afford to buffer and the latency you can tolerate.
Read the code
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
for id in 0..3 {
let tx = tx.clone();
thread::spawn(move || {
tx.send(format!("worker {id}")).unwrap();
});
}
drop(tx); // so the loop can end
for message in rx {
println!("{message}");
}Ownership transfers with the message, so no lock is needed.
Practice starter
use std::sync::mpsc;
let (tx, rx) = mpsc::channel::<String>();
let worker = tx.clone();
for message in rx { println!("{message}"); }Try it
Send results from several threads to one collector.
What success looks like: The receiving loop finishes without a sentinel value.
Check your understanding
Why might that loop never end?
Reveal the answer
- A channel receiver loops forever by design
- tx and its clone worker are still alive, so the channel never closes
- The receiver has to be declared mut to iterate
Every live sender keeps the channel open; drop the ones you do not use.
Go deeper
Common misconception: “A receiver loop runs forever unless you send a sentinel message.”
The loop ends when the last sender is dropped. Iterating a receiver stops once every Sender clone is gone, so the example needs drop(tx), and the practice must drop worker too.
- Count the senders:
mpsc::channelreturns onetx, and each pass of the loop clones it for a worker, so four senders are made in all; a worker may exit and drop its clone before the next one is made. - Follow a message:
sendmoves theStringinto the channel. The three workers have no guaranteed order, so the lines can print in any order. - Close the channel:
drop(tx)removes the original, and each worker drops its clone on exit. With no senders left, theforloop ends.
Transfer challenge: Delete drop(tx) from the example and predict what the program does. Then restore it and have main send a fourth message first; predict how many lines print.
Connections
- Threads: spawn, join, and move closures
- Shared State: Mutex, RwLock, and Arc
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Channels (courseId "concurrency", lessonId "channels") Link: https://crabrix.com/learn/concurrency/channels/ Goal: A receiver iterator finishes after every sender is dropped and all queued messages have been received. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=concurrency/channels) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.