Bounded Channels With sync_channel

Bounded sync_channel capacity blocks the producer when the consumer lags, giving you backpressure without an external queue crate.

RustResilience

Code

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

fn main() {
    // 缓冲区容量 2:写满后 send 阻塞,形成背压
    let (tx, rx) = sync_channel::<u32>(2);

    let producer = thread::spawn(move || {
        for item in 0..6 {
            tx.send(item).expect("receiver dropped");
            println!("sent {item}");
        }
    });

    // 慢消费者:发送端会被容量挡住,而不是无限堆内存
    for value in rx {
        thread::sleep(Duration::from_millis(10));
        println!("handled {value}");
    }
    producer.join().expect("producer panicked");
}

How it works

Bounded Channels With sync_channel reduces to the function main.

Iteration happens inside for item in 0..6 — everything outside it runs once.

Putting it to use

Running the file prints labeled results such as sent, handled — each operation’s effect is visible in the output.

Core lines

let producer = thread::spawn(move || {
for item in 0..6 {
tx.send(item).expect("receiver dropped");
println!("sent {item}");
}
});

Interactive Tools for This Topic

FAQ

What does Bounded Channels With sync_channel print when run?
No setup needed: run the file and look for labeled lines like `sent`, `handled` in the output.