Skip to content

Commit c9e5e6a

Browse files
committed
Auto merge of #77154 - fusion-engineering-forks:lazy-stdio, r=dtolnay
Remove std::io::lazy::Lazy in favour of SyncOnceCell The (internal) std::io::lazy::Lazy was used to lazily initialize the stdout and stdin buffers (and mutexes). It uses atexit() to register a destructor to flush the streams on exit, and mark the streams as 'closed'. Using the stream afterwards would result in a panic. Stdout uses a LineWriter which contains a BufWriter that will flush the buffer on drop. This one is important to be executed during shutdown, to make sure no buffered output is lost. It also forbids access to stdout afterwards, since the buffer is already flushed and gone. Stdin uses a BufReader, which does not implement Drop. It simply forgets any previously read data that was not read from the buffer yet. This means that in the case of stdin, the atexit() function's only effect is making stdin inaccessible to the program, such that later accesses result in a panic. This is uncessary, as it'd have been safe to access stdin during shutdown of the program. --- This change removes the entire io::lazy module in favour of SyncOnceCell. SyncOnceCell's fast path is much faster (a single atomic operation) than locking a sys_common::Mutex on every access like Lazy did. However, SyncOnceCell does not use atexit() to drop the contained object during shutdown. As noted above, this is not a problem for stdin. It simply means stdin is now usable during shutdown. The atexit() call for stdout is moved to the stdio module. Unlike the now-removed Lazy struct, SyncOnceCell does not have a 'gone and unusable' state that panics. Instead of adding this again, this simply replaces the buffer with one with zero capacity. This effectively flushes the old buffer *and* makes any writes afterwards pass through directly without touching a buffer, making print!() available during shutdown without panicking. --- In addition, because the contents of the SyncOnceCell are no longer dropped, we can now use `&'static` instead of `Arc` in `Stdout` and `Stdin`. This also saves two levels of indirection in `stdin()` and `stdout()`, since Lazy effectively stored a `Box<Arc<T>>`, and SyncOnceCell stores the `T` directly.
2 parents 62fe055 + 6b8b9c4 commit c9e5e6a

File tree

5 files changed

+60
-100
lines changed

5 files changed

+60
-100
lines changed

library/std/src/io/lazy.rs

-63
This file was deleted.

library/std/src/io/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,6 @@ mod buffered;
285285
mod cursor;
286286
mod error;
287287
mod impls;
288-
mod lazy;
289288
pub mod prelude;
290289
mod stdio;
291290
mod util;

library/std/src/io/stdio.rs

+40-36
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ use crate::io::prelude::*;
77

88
use crate::cell::RefCell;
99
use crate::fmt;
10-
use crate::io::lazy::Lazy;
1110
use crate::io::{self, BufReader, Initializer, IoSlice, IoSliceMut, LineWriter};
12-
use crate::sync::{Arc, Mutex, MutexGuard, Once};
11+
use crate::lazy::SyncOnceCell;
12+
use crate::sync::{Mutex, MutexGuard};
1313
use crate::sys::stdio;
14+
use crate::sys_common;
1415
use crate::sys_common::remutex::{ReentrantMutex, ReentrantMutexGuard};
1516
use crate::thread::LocalKey;
1617

@@ -217,7 +218,7 @@ fn handle_ebadf<T>(r: io::Result<T>, default: T) -> io::Result<T> {
217218
/// ```
218219
#[stable(feature = "rust1", since = "1.0.0")]
219220
pub struct Stdin {
220-
inner: Arc<Mutex<BufReader<StdinRaw>>>,
221+
inner: &'static Mutex<BufReader<StdinRaw>>,
221222
}
222223

223224
/// A locked reference to the `Stdin` handle.
@@ -292,15 +293,11 @@ pub struct StdinLock<'a> {
292293
/// ```
293294
#[stable(feature = "rust1", since = "1.0.0")]
294295
pub fn stdin() -> Stdin {
295-
static INSTANCE: Lazy<Mutex<BufReader<StdinRaw>>> = Lazy::new();
296-
return Stdin {
297-
inner: unsafe { INSTANCE.get(stdin_init).expect("cannot access stdin during shutdown") },
298-
};
299-
300-
fn stdin_init() -> Arc<Mutex<BufReader<StdinRaw>>> {
301-
// This must not reentrantly access `INSTANCE`
302-
let stdin = stdin_raw();
303-
Arc::new(Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin)))
296+
static INSTANCE: SyncOnceCell<Mutex<BufReader<StdinRaw>>> = SyncOnceCell::new();
297+
Stdin {
298+
inner: INSTANCE.get_or_init(|| {
299+
Mutex::new(BufReader::with_capacity(stdio::STDIN_BUF_SIZE, stdin_raw()))
300+
}),
304301
}
305302
}
306303

@@ -476,7 +473,7 @@ pub struct Stdout {
476473
// FIXME: this should be LineWriter or BufWriter depending on the state of
477474
// stdout (tty or not). Note that if this is not line buffered it
478475
// should also flush-on-panic or some form of flush-on-abort.
479-
inner: Arc<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>>,
476+
inner: &'static ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>,
480477
}
481478

482479
/// A locked reference to the `Stdout` handle.
@@ -534,19 +531,27 @@ pub struct StdoutLock<'a> {
534531
/// ```
535532
#[stable(feature = "rust1", since = "1.0.0")]
536533
pub fn stdout() -> Stdout {
537-
static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> = Lazy::new();
538-
return Stdout {
539-
inner: unsafe { INSTANCE.get(stdout_init).expect("cannot access stdout during shutdown") },
540-
};
541-
542-
fn stdout_init() -> Arc<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> {
543-
// This must not reentrantly access `INSTANCE`
544-
let stdout = stdout_raw();
545-
unsafe {
546-
let ret = Arc::new(ReentrantMutex::new(RefCell::new(LineWriter::new(stdout))));
547-
ret.init();
548-
ret
549-
}
534+
static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<LineWriter<StdoutRaw>>>> =
535+
SyncOnceCell::new();
536+
Stdout {
537+
inner: INSTANCE.get_or_init(|| unsafe {
538+
let _ = sys_common::at_exit(|| {
539+
if let Some(instance) = INSTANCE.get() {
540+
// Flush the data and disable buffering during shutdown
541+
// by replacing the line writer by one with zero
542+
// buffering capacity.
543+
// We use try_lock() instead of lock(), because someone
544+
// might have leaked a StdoutLock, which would
545+
// otherwise cause a deadlock here.
546+
if let Some(lock) = instance.try_lock() {
547+
*lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
548+
}
549+
}
550+
});
551+
let r = ReentrantMutex::new(RefCell::new(LineWriter::new(stdout_raw())));
552+
r.init();
553+
r
554+
}),
550555
}
551556
}
552557

@@ -741,16 +746,15 @@ pub fn stderr() -> Stderr {
741746
//
742747
// This has the added benefit of allowing `stderr` to be usable during
743748
// process shutdown as well!
744-
static INSTANCE: ReentrantMutex<RefCell<StderrRaw>> =
745-
unsafe { ReentrantMutex::new(RefCell::new(stderr_raw())) };
746-
747-
// When accessing stderr we need one-time initialization of the reentrant
748-
// mutex. Afterwards we can just always use the now-filled-in `INSTANCE` value.
749-
static INIT: Once = Once::new();
750-
INIT.call_once(|| unsafe {
751-
INSTANCE.init();
752-
});
753-
Stderr { inner: &INSTANCE }
749+
static INSTANCE: SyncOnceCell<ReentrantMutex<RefCell<StderrRaw>>> = SyncOnceCell::new();
750+
751+
Stderr {
752+
inner: INSTANCE.get_or_init(|| unsafe {
753+
let r = ReentrantMutex::new(RefCell::new(stderr_raw()));
754+
r.init();
755+
r
756+
}),
757+
}
754758
}
755759

756760
impl Stderr {

src/test/ui/stdout-during-shutdown.rs

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// run-pass
2+
// check-run-results
3+
// ignore-emscripten
4+
5+
// Emscripten doesn't flush its own stdout buffers on exit, which would fail
6+
// this test. So this test is disabled on this platform.
7+
// See https://emscripten.org/docs/getting_started/FAQ.html#what-does-exiting-the-runtime-mean-why-don-t-atexit-s-run
8+
9+
#![feature(rustc_private)]
10+
11+
extern crate libc;
12+
13+
fn main() {
14+
extern "C" fn bye() {
15+
print!(", world!");
16+
}
17+
unsafe { libc::atexit(bye) };
18+
print!("hello");
19+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
hello, world!

0 commit comments

Comments
 (0)