Channels
A channel moves values from sending threads to a receiving thread. Rust's standard channel is multi-producer, single-consumer (mpsc). The value is moved, not shared.
Detailed Explanation
Message passing is the alternative to shared memory. Instead of two threads writing a Mutex<Vec>, one thread sends work items and the other recvs them. Ownership moves with the message. The borrow checker is happy because there is no shared &mut.
std::sync::mpsc::channel creates a pair (Sender, Receiver). Sender is Clone: several producers can send. Receiver is not Clone: one consumer. send is non-blocking for an unbounded channel until memory runs out. recv blocks until a message arrives or every sender has been dropped, then it returns Err. That hang-up is how you shut down a worker: drop all senders, let the loop end.
A bounded alternative is sync_channel(n). send blocks when n messages are already waiting. Backpressure is the feature: a fast producer cannot grow RAM without limit. Tokio has mpsc, broadcast, watch, and oneshot for async tasks; those are not the std types, and they are what you want inside an async runtime.
Channels do not make a distributed system. They are in-process queues. They do not persist. A panic on the receiver drops unread messages. A cycle of channels can deadlock the same way a cycle of mutexes can.
When you reach for a channel: pipelines, worker pools, decoupling production from consumption. When you reach for a mutex: the threads must see the same mutable store. When you reach for tokio's channels: the waiters are tasks, not OS threads.
Unbounded channels plus a slow consumer are how services grow RSS. Measure queue depth. If you cannot bound the channel, bound the producer (a semaphore, a pool of in-flight requests). A channel is a queue with a type; it is not a flow-control policy unless you pick the bounded form and handle a full send.
Code Examples
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
tx.send("ada").unwrap();
});
println!("{}", rx.recv().unwrap()); // prints: ada
}Common Gotchas
An unbounded channel is a memory leak under load
If the consumer is slow, `send` keeps allocating. Use `sync_channel` or a bounded tokio channel.
`recv` errors when every sender is dropped
That is the shutdown signal. Keep a sender alive by accident and the worker never exits.
The std receiver is single-consumer
You cannot `clone` it. Fan-out needs multiple channels, a pool, or a different crate.
Do not block on `recv` inside a Tokio worker
Use `tokio::sync::mpsc` and `.await`.