]> git.lizzy.rs Git - rust.git/commitdiff
std: fix cleanup for uninitialized stdout (#101375)
authorjoboet <jonasboettiger@icloud.com>
Mon, 5 Sep 2022 07:08:07 +0000 (09:08 +0200)
committerjoboet <jonasboettiger@icloud.com>
Mon, 5 Sep 2022 07:08:07 +0000 (09:08 +0200)
library/std/src/io/stdio.rs

index dd4ff4952fde9f8bc641aa1cf316d72889487a8b..91cff3217d21bce19ad24ebdd7632d66729a91e5 100644 (file)
@@ -607,15 +607,24 @@ pub fn stdout() -> Stdout {
     }
 }
 
+// Flush the data and disable buffering during shutdown
+// by replacing the line writer by one with zero
+// buffering capacity.
 pub fn cleanup() {
-    // Flush the data and disable buffering during shutdown
-    // by replacing the line writer by one with zero
-    // buffering capacity.
-    // We use try_lock() instead of lock(), because someone
-    // might have leaked a StdoutLock, which would
-    // otherwise cause a deadlock here.
-    if let Some(lock) = STDOUT.get().and_then(ReentrantMutex::try_lock) {
-        *lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
+    let mut initialized = false;
+    let stdout = STDOUT.get_or_init(|| {
+        initialized = true;
+        ReentrantMutex::new(RefCell::new(LineWriter::with_capacity(0, stdout_raw())))
+    });
+
+    if !initialized {
+        // The buffer was previously initialized, overwrite it here.
+        // We use try_lock() instead of lock(), because someone
+        // might have leaked a StdoutLock, which would
+        // otherwise cause a deadlock here.
+        if let Some(lock) = stdout.try_lock() {
+            *lock.borrow_mut() = LineWriter::with_capacity(0, stdout_raw());
+        }
     }
 }