about summary refs log tree commit diff
diff options
context:
space:
mode:
authorsigaloid <69441971+sigaloid@users.noreply.github.com>2022-07-25 21:58:30 -0400
committersigaloid <69441971+sigaloid@users.noreply.github.com>2022-07-25 21:58:30 -0400
commitfab36d1713504824be4eefdd7614cf9e79ca7358 (patch)
treeb5683bbd859bf27a6924425af77cf1f760e15788
parenta86705942c4cfaaee60f2e7308ca2bca703a710f (diff)
downloadrust-fab36d1713504824be4eefdd7614cf9e79ca7358.tar.gz
rust-fab36d1713504824be4eefdd7614cf9e79ca7358.zip
Add comments about stdout locking
-rw-r--r--library/std/src/macros.rs22
1 files changed, 22 insertions, 0 deletions
diff --git a/library/std/src/macros.rs b/library/std/src/macros.rs
index 0cb21ef53b1..00473f50a63 100644
--- a/library/std/src/macros.rs
+++ b/library/std/src/macros.rs
@@ -27,12 +27,23 @@ macro_rules! panic {
 /// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
 /// immediately.
 ///
+/// The `print!` macro will lock the standard output on each call. If you call
+/// `print!` within a hot loop, this behavior may be the bottleneck of the loop.
+/// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
+/// ```
+/// use std::io::{stdout, Write};
+///
+/// let mut lock = stdout().lock();
+/// write!(lock, "hello world").unwrap();
+/// ```
+///
 /// Use `print!` only for the primary output of your program. Use
 /// [`eprint!`] instead to print error and progress messages.
 ///
 /// [flush]: crate::io::Write::flush
 /// [`println!`]: crate::println
 /// [`eprint!`]: crate::eprint
+/// [lock]: crate::io::Stdout
 ///
 /// # Panics
 ///
@@ -75,11 +86,22 @@ macro_rules! print {
 /// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
 /// See [`std::fmt`] for more information.
 ///
+/// The `println!` macro will lock the standard output on each call. If you call
+/// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
+/// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
+/// ```
+/// use std::io::{stdout, Write};
+///
+/// let mut lock = stdout().lock();
+/// writeln!(lock, "hello world").unwrap();
+/// ```
+///
 /// Use `println!` only for the primary output of your program. Use
 /// [`eprintln!`] instead to print error and progress messages.
 ///
 /// [`std::fmt`]: crate::fmt
 /// [`eprintln!`]: crate::eprintln
+/// [lock]: crate::io::Stdout
 ///
 /// # Panics
 ///