diff --git a/tokio/src/io/stdout.rs b/tokio/src/io/stdout.rs index 7636fe9708c..b4621469202 100644 --- a/tokio/src/io/stdout.rs +++ b/tokio/src/io/stdout.rs @@ -33,6 +33,31 @@ cfg_io_std! { /// Ok(()) /// } /// ``` + /// + /// The following is an example of using `stdio` with loop. + /// + /// ``` + /// use tokio::io::{self, AsyncWriteExt}; + /// + /// #[tokio::main] + /// async fn main() { + /// let messages = vec!["hello", " world\n"]; + /// + /// // When you use `stdio` in a loop, it is recommended to create + /// // a single `stdio` instance outside the loop and call a write + /// // operation against that instance on each loop. + /// // + /// // Repeatedly creating `stdout` instances inside the loop and + /// // writing to that handle could result in mangled output since + /// // each write operation is handled by a different blocking thread. + /// let mut stdout = io::stdout(); + /// + /// for message in &messages { + /// stdout.write_all(message.as_bytes()).await.unwrap(); + /// stdout.flush().await.unwrap(); + /// } + /// } + /// ``` #[derive(Debug)] pub struct Stdout { std: SplitByUtf8BoundaryIfWindows>, @@ -64,6 +89,31 @@ cfg_io_std! { /// Ok(()) /// } /// ``` + /// + /// The following is an example of using `stdio` with loop. + /// + /// ``` + /// use tokio::io::{self, AsyncWriteExt}; + /// + /// #[tokio::main] + /// async fn main() { + /// let messages = vec!["hello", " world\n"]; + /// + /// // When you use `stdio` in a loop, it is recommended to create + /// // a single `stdio` instance outside the loop and call a write + /// // operation against that instance on each loop. + /// // + /// // Repeatedly creating `stdout` instances inside the loop and + /// // writing to that handle could result in mangled output since + /// // each write operation is handled by a different blocking thread. + /// let mut stdout = io::stdout(); + /// + /// for message in &messages { + /// stdout.write_all(message.as_bytes()).await.unwrap(); + /// stdout.flush().await.unwrap(); + /// } + /// } + /// ``` pub fn stdout() -> Stdout { let std = io::stdout(); Stdout {