Rust mpsc — sync_channel buffers and unbounded channel

Contents

  1. 1. Rules
  2. 2. sync_channel — buffer size 0 (handshake)
  3. 3. sync_channel — larger buffer (mpsc)
  4. 4. channel (unbounded)
  5. 5. Concurrency safety

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::sync::mpsc::sync_channel;
use std::thread;

fn main() {
let (sender, receiver) = sync_channel(0);
let (sender2, receiver2) = sync_channel(0);

let cnt = 3;
let t1 = thread::spawn({
move || {
for _ in 0..cnt {
print!("1 ");
// After printing, tell t2's receiver to go
sender.send(2).unwrap();
// Block until t2 finishes its print
receiver2.recv().unwrap();
}
}
});

let t2 = thread::spawn({
move || {
for _ in 0..cnt {
// Block until t1 has sent after its print
receiver.recv().unwrap();
print!("2 ");
// Tell t1 it can print again
sender2.send(1).unwrap();
}
}
});

t1.join().unwrap();
t2.join().unwrap();
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::sync::mpsc::sync_channel;
use std::thread;

fn main() {
let (sender, receiver) = sync_channel(3);

let sender2 = sender.clone();
let sender3 = sender.clone();
thread::spawn(move || sender.send(1).unwrap());
thread::spawn(move || sender2.clone().send(2).unwrap());

drop(sender3); // Ensures the third recv can complete
println!("{:?}", receiver.recv().unwrap());
println!("{:?}", receiver.recv().unwrap());
println!("{:?}", receiver.recv());
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::sync::mpsc::{channel, sync_channel};
use std::thread;

fn main() {
// let (sender, receiver) = sync_channel(1); // buffer 1 — may not print "send no block"
let (sender, receiver) = channel(); // unbounded — send returns immediately

thread::spawn(move || {
sender.send(1).unwrap();
sender.send(2).unwrap();
sender.send(3).unwrap();
println!("send no block");
});

println!("{:?}", receiver.recv().unwrap());
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
use std::sync::mpsc::{channel, Receiver, RecvError, TryRecvError};

fn main() {
let (sender, receiver) = channel();
fn try_recv_with_log(receiver: &Receiver<i32>) {
match receiver.try_recv() {
Ok(v) => println!("{:?}", v),
Err(TryRecvError::Empty) => println!("error: Empty"),
Err(TryRecvError::Disconnected) => println!("error: Disconnected"),
}
}
// error: Empty
try_recv_with_log(&receiver);
sender.send(1).unwrap();
receiver.recv().unwrap();
drop(sender);
// error: Disconnected
try_recv_with_log(&receiver);
}

Concurrency safety

1
2
3
4
5
unsafe impl<T: Send> Send for Sender<T> {}
unsafe impl<T: Send> Sync for Sender<T> {}

unsafe impl<T: Send> Send for Receiver<T> {}
impl<T> !Sync for Receiver<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