Home

StdoutLock

StdoutLock is a type in Rust's standard library that represents a locked handle to the program’s standard output. It is obtained by calling std::io::stdout().lock(), which acquires an internal mutex around the shared stdout. While the lock is held, writes performed via the StdoutLock are serialized with respect to other potential writers to stdout, preventing interleaving of output from multiple threads.

StdoutLock implements the Write trait, so you can use the usual write!, writeln!, and related macros with

Lifetime-wise, StdoutLock<'a> borrows from the Stdout handle and cannot outlive it. A common pattern is to obtain

Performance and correctness: locking stdout once for a group of writes can be more efficient than locking

Error handling: writes through a StdoutLock return a Result, allowing callers to unwrap or propagate errors

it.
The
guard
is
released
when
the
StdoutLock
is
dropped,
at
which
point
the
underlying
lock
is
released
and
buffered
data
may
be
flushed.
This
makes
it
convenient
to
bundle
multiple
writes
under
a
single
lock.
a
lock
for
a
scope
and
perform
several
writes
before
dropping
it.
This
provides
thread-safe
access
to
stdout
without
requiring
per-write
locking.
for
every
single
write,
especially
in
multithreaded
programs.
However,
holding
the
lock
for
long
operations
can
cause
other
threads
to
block,
so
the
lock
scope
should
be
kept
reasonably
short
and
focused.
as
needed.
StdoutLock
is
a
thin
synchronization
wrapper
around
the
standard
output,
ensuring
safe,
serialized
access
across
threads
while
preserving
familiar
Write-based
idioms.