expression

Bounded async message queue

Use a queue with a fixed number of message slots to connect producers and a consumer. Sending awaits capacity when the queue is full. A slot count is not a byte limit. The consumer must run while producers are waiting. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): 4 7 Common mistake: Filling a bounded queue and awaiting another send before allowing any receive.

Formal Syntax & Structure

rust syntaxrust
tokio::sync::mpsc::channel::<T>(capacity)

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() {    let (tx, mut rx) = tokio::sync::mpsc::channel(2);    tx.send(4).await.unwrap();    tx.send(7).await.unwrap();    drop(tx);    while let Some(n) = rx.recv().await { println!("{n}"); }}
Rust Reference