Sync Channel Backpressure Blocks Send

Cap a channel with sync_channel so producer sends block while the consumer is behind: capacity 1 forces strict send and receive alternation.

RustResilience

Code

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

fn main() {
    // 有界通道容量为 1:send 在缓冲满时阻塞,形成天然背压
    let (tx, rx) = sync_channel::<i32>(1);

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

    // 消费者故意放慢:容量 1 强制收发严格交替,不会堆积
    for _ in 0..4 {
        thread::sleep(Duration::from_millis(20));
        println!("received {}", rx.recv().expect("sender alive"));
    }
    producer.join().expect("producer panicked");
}

How the file reaches its output

Under the hood: the function main.

The loop for item in 0..4 is the only repeated construct.

Caveats

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

Putting it to use

Entry signature: fn main()

The file’s steps show up in the output as sent, received.

Core lines

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

Interactive Tools for This Topic

FAQ

What does Sync Channel Backpressure Blocks Send print when run?
Running the file directly is enough — expect labeled output lines such as `sent`, `received`.