sync_channel Zero Capacity Rendezvous

A sync_channel with capacity zero has no buffer, so every send blocks until the receiver takes the value, turning each message into a synchronous handoff.

RustResilience

Code

rustsnippet
26 lines
use std::sync::mpsc::sync_channel;
use std::thread;
use std::time::Duration;

fn main() {
    // 容量 0:没有缓冲区,每次 send 都要等 recv 到场,形成会合握手
    let (tx, rx) = sync_channel::<u32>(0);

    let producer = thread::spawn(move || {
        let mut delivered = Vec::new();
        for msg in [1, 2, 3] {
            tx.send(msg).expect("receiver alive");
            delivered.push(msg); // 能走到这里说明对端已取走上一个值
        }
        delivered
    });

    for i in 0..3 {
        thread::sleep(Duration::from_millis(20));
        let value = rx.recv().expect("sender alive");
        println!("recv {} -> value {value}", i + 1);
    }

    let delivered = producer.join().expect("producer panicked");
    println!("producer delivered: {delivered:?}");
}

What the code does

Structurally, expect the function main and nothing else.

Iteration happens inside for msg in [1, 2, 3] — everything outside it runs once.

Points of care

  • Nothing arrives from a registry; the language ships every API used.

Applying it

Entry signature: fn main()

Running the file prints a marker per step: recv, producer delivered:.

Statements that carry the weight

let producer = thread::spawn(move || {
    let mut delivered = Vec::new();
    for msg in [1, 2, 3] {
        tx.send(msg).expect("receiver alive");
        delivered.push(msg); // 能走到这里说明对端已取走上一个值
    }
    delivered
});

Interactive Tools for This Topic

FAQ

What does sync_channel Zero Capacity Rendezvous print when run?
The script runs standalone; its 2 labeled outputs include `recv`, `producer delivered:`.