expression
Drain a small pipe concurrently
A finite pipe needs its reader to progress while a large write waits. Join the two futures and close the writing direction to let a consumer reading to EOF finish. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): abcdef Common mistake: Waiting for all bytes to fit in the pipe before reading.
Formal Syntax & Structure
rust syntaxrust
tokio::join!(producer, consumer)Working Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { use tokio::io::{AsyncReadExt, AsyncWriteExt}; let (mut a, mut b) = tokio::io::duplex(2); let send = async { a.write_all(b"abcdef").await.unwrap(); a.shutdown().await.unwrap(); }; let receive = async { let mut buf = Vec::new(); b.read_to_end(&mut buf).await.unwrap(); buf }; let (_, bytes) = tokio::join!(send, receive); println!("{}", String::from_utf8(bytes).unwrap());}