Function zng_task::channel::rendezvous

source ·
pub fn rendezvous<T>() -> (Sender<T>, Receiver<T>)
Expand description

Create a bounded channel with 0 capacity.

Rendezvous channels always awaits until the message is received to return from send, there is no buffer.

§Examples

The example spawns two parallel tasks, the sender and receiver handshake when transferring the message, the receiver takes 2 seconds to receive, so the sender takes 2 seconds to send.

use zng_task::{self as task, channel};

let (sender, receiver) = channel::rendezvous();

task::spawn(async move {
    loop {
        let t = INSTANT.now();

        if let Err(e) = sender.send("the stuff").await {
            eprintln!(r#"failed to send "{}", no receiver connected"#, e.0);
            break;
        }

        assert!(t.elapsed() >= 2.secs());
    }
});
task::spawn(async move {
    loop {
        task::deadline(2.secs()).await;

        match receiver.recv().await {
            Ok(msg) => println!(r#"got "{msg}""#),
            Err(_) => {
                eprintln!("no sender connected");
                break;
            }
        }
    }
});