Function tokio::sync::mpsc::channel[][src]

pub fn channel<T>(buffer: usize) -> (Sender<T>, Receiver<T>)

Creates a bounded mpsc channel for communicating between asynchronous tasks, returning the sender/receiver halves.

All data sent on Sender will become available on Receiver in the same order as it was sent.

The Sender can be cloned to send to the same channel from multiple code locations. Only one Receiver is supported.

If the Receiver is disconnected while trying to send, the send method will return a SendError. Similarly, if Sender is disconnected while trying to recv, the recv method will return a RecvError.

Examples

use tokio::sync::mpsc;

#[tokio::main]
async fn main() {
    let (mut tx, mut rx) = mpsc::channel(100);

    tokio::spawn(async move {
        for i in 0..10 {
            if let Err(_) = tx.send(i).await {
                println!("receiver dropped");
                return;
            }
        }
    });

    while let Some(i) = rx.recv().await {
        println!("got = {}", i);
    }
}