Contents
Rust’s sync module exposes mpsc (multi-producer, single-consumer) channels—message passing instead of locking shared memory. That’s the style Rob Pike pushed:
Don’t communicate by sharing memory; share memory by communicating. (R. Pike)
Below: bounded sync_channel and the unbounded channel, plus how Send/Sync show up on the handles.
Rules
Most channel designs share the same contract:
- Producers send, consumers recv, usually FIFO via an internal queue.
- Receivers block when empty until a message arrives or the channel closes.
- A buffer size caps in-flight messages.
- When the buffer is full, senders block until something is received.
So production generally leads consumption, and ordering is first-in-first-out.
sync_channel — buffer size 0 (handshake)
A buffer of 0 means every send blocks until a matching recv—classic back-pressure, one in flight at a time.
That’s handy for enforcing order. Two zero-capacity channels can alternate 1 and 2:
1 | use std::sync::mpsc::sync_channel; |
Criss-cross send/recv on two channels serializes the prints much like alternating lock handoffs.
sync_channel — larger buffer (mpsc)
With a positive buffer, you get real mpsc: multiple senders, one receiver, up to N messages queued (often a preallocated slot array).
When the buffer fills, senders wait. Receivers still block on an empty queue.
Remember dropping the last sender closes the channel so blocked recv can return Err:
1 | use std::sync::mpsc::sync_channel; |
channel (unbounded)
Once sync_channel clicks, channel is the same idea with an effectively unbounded buffer (linked list that grows). Sends don’t block for capacity; only recv blocks when empty.
1 | use std::sync::mpsc::{channel, sync_channel}; |
For non-blocking checks, use try_recv:
TryRecvError::Empty— no message yet, channel still connected.TryRecvError::Disconnected— all senders gone; no more messages ever.
1 | use std::sync::mpsc::{channel, Receiver, RecvError, TryRecvError}; |
Concurrency safety
1 | unsafe impl<T: Send> Send for Sender<T> {} |
How does Rust keep channels sound?
Sender<T> is both Send and Sync: the queue can move across threads and be shared, so multiple threads can send concurrently. T: Send so owned messages cross thread boundaries safely.
Receiver<T> is Send but not Sync—only one thread should own the receiver and drain the queue.
Again, marker traits encode the rules at compile time so you get fearless concurrency without ad-hoc comments.
More Rust concurrency notes: Rust category.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
