Channel Buffering in Rust

use std::sync::mpsc;

fn main() {
    // Here we create a channel of strings buffering up to 2 values.
    let (tx, rx) = mpsc::sync_channel(2);

    // Because this channel is buffered, we can send these
    // values into the channel without a corresponding
    // concurrent receive.
    tx.send("buffered".to_string()).unwrap();
    tx.send("channel".to_string()).unwrap();

    // Later we can receive these two values as usual.
    println!("{}", rx.recv().unwrap());
    println!("{}", rx.recv().unwrap());
}

By default, channels in Rust are unbuffered, meaning that they will only accept sends if there is a corresponding receiver ready to receive the sent value. Buffered channels accept a limited number of values without a corresponding receiver for those values.

In this example, we use the mpsc::sync_channel function to create a buffered channel with a capacity of 2. The mpsc module in Rust stands for Multi-Producer, Single-Consumer, which provides a way to create channels for message passing between threads.

We create a channel of strings buffering up to 2 values. Because this channel is buffered, we can send these values into the channel without a corresponding concurrent receive.

Later, we can receive these two values as usual using the recv method on the receiver end of the channel.

To run the program, save it as channel_buffering.rs and use rustc to compile it:

$ rustc channel_buffering.rs
$ ./channel_buffering
buffered
channel

This example demonstrates how to use buffered channels in Rust for asynchronous communication between parts of your program.