pub fn bounded<T>(capacity: usize) -> (Sender<T>, Receiver<T>)
Expand description
Create a channel with a maximum capacity.
Bounded channels send
until the channel reaches its capacity then it awaits until a message
is received before sending another message.
ยงExamples
The example spawns two parallel tasks, the receiver task takes a while to start receiving but then rapidly consumes the 2 messages in the buffer and unblocks the sender to send more messages.
use zng_task::{self as task, channel};
let (sender, receiver) = channel::bounded(2);
task::spawn(async move {
for msg in ["Hello!", "Data!"].into_iter().cycle() {
task::deadline(300.ms()).await;
if let Err(e) = sender.send(msg).await {
eprintln!("no receiver connected, the message `{}` was not send", e.0);
break;
}
}
});
task::spawn(async move {
task::deadline(5.secs()).await;
loop {
match receiver.recv().await {
Ok(msg) => println!("{msg}"),
Err(_) => {
eprintln!("no message in channel and no sender connected");
break;
}
}
}
});