Skip to content

Commit fab36d1

Browse files
committed
Add comments about stdout locking
1 parent a867059 commit fab36d1

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

library/std/src/macros.rs

+22
Original file line numberDiff line numberDiff line change
@@ -27,12 +27,23 @@ macro_rules! panic {
2727
/// necessary to use [`io::stdout().flush()`][flush] to ensure the output is emitted
2828
/// immediately.
2929
///
30+
/// The `print!` macro will lock the standard output on each call. If you call
31+
/// `print!` within a hot loop, this behavior may be the bottleneck of the loop.
32+
/// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
33+
/// ```
34+
/// use std::io::{stdout, Write};
35+
///
36+
/// let mut lock = stdout().lock();
37+
/// write!(lock, "hello world").unwrap();
38+
/// ```
39+
///
3040
/// Use `print!` only for the primary output of your program. Use
3141
/// [`eprint!`] instead to print error and progress messages.
3242
///
3343
/// [flush]: crate::io::Write::flush
3444
/// [`println!`]: crate::println
3545
/// [`eprint!`]: crate::eprint
46+
/// [lock]: crate::io::Stdout
3647
///
3748
/// # Panics
3849
///
@@ -75,11 +86,22 @@ macro_rules! print {
7586
/// This macro uses the same syntax as [`format!`], but writes to the standard output instead.
7687
/// See [`std::fmt`] for more information.
7788
///
89+
/// The `println!` macro will lock the standard output on each call. If you call
90+
/// `println!` within a hot loop, this behavior may be the bottleneck of the loop.
91+
/// To avoid this, lock stdout with [`io::stdout().lock()`][lock]:
92+
/// ```
93+
/// use std::io::{stdout, Write};
94+
///
95+
/// let mut lock = stdout().lock();
96+
/// writeln!(lock, "hello world").unwrap();
97+
/// ```
98+
///
7899
/// Use `println!` only for the primary output of your program. Use
79100
/// [`eprintln!`] instead to print error and progress messages.
80101
///
81102
/// [`std::fmt`]: crate::fmt
82103
/// [`eprintln!`]: crate::eprintln
104+
/// [lock]: crate::io::Stdout
83105
///
84106
/// # Panics
85107
///

0 commit comments

Comments
 (0)