@@ -13,7 +13,6 @@ use crate::pin::Pin;
1313use crate :: sync:: atomic:: { AtomicBool , Ordering } ;
1414use crate :: sync:: { Arc , Mutex , MutexGuard } ;
1515use crate :: sys:: stdio;
16- use crate :: sys_common;
1716use crate :: sys_common:: remutex:: { ReentrantMutex , ReentrantMutexGuard } ;
1817
1918type LocalStream = Arc < Mutex < Vec < u8 > > > ;
@@ -508,6 +507,8 @@ pub struct StdoutLock<'a> {
508507 inner : ReentrantMutexGuard < ' a , RefCell < LineWriter < StdoutRaw > > > ,
509508}
510509
510+ static STDOUT : SyncOnceCell < ReentrantMutex < RefCell < LineWriter < StdoutRaw > > > > = SyncOnceCell :: new ( ) ;
511+
511512/// Constructs a new handle to the standard output of the current process.
512513///
513514/// Each handle returned is a reference to a shared global buffer whose access
@@ -549,34 +550,28 @@ pub struct StdoutLock<'a> {
549550/// ```
550551#[ stable( feature = "rust1" , since = "1.0.0" ) ]
551552pub fn stdout ( ) -> Stdout {
552- static INSTANCE : SyncOnceCell < ReentrantMutex < RefCell < LineWriter < StdoutRaw > > > > =
553- SyncOnceCell :: new ( ) ;
554-
555- fn cleanup ( ) {
556- if let Some ( instance) = INSTANCE . get ( ) {
557- // Flush the data and disable buffering during shutdown
558- // by replacing the line writer by one with zero
559- // buffering capacity.
560- // We use try_lock() instead of lock(), because someone
561- // might have leaked a StdoutLock, which would
562- // otherwise cause a deadlock here.
563- if let Some ( lock) = Pin :: static_ref ( instance) . try_lock ( ) {
564- * lock. borrow_mut ( ) = LineWriter :: with_capacity ( 0 , stdout_raw ( ) ) ;
565- }
566- }
567- }
568-
569553 Stdout {
570- inner : Pin :: static_ref ( & INSTANCE ) . get_or_init_pin (
571- || unsafe {
572- let _ = sys_common:: at_exit ( cleanup) ;
573- ReentrantMutex :: new ( RefCell :: new ( LineWriter :: new ( stdout_raw ( ) ) ) )
574- } ,
554+ inner : Pin :: static_ref ( & STDOUT ) . get_or_init_pin (
555+ || unsafe { ReentrantMutex :: new ( RefCell :: new ( LineWriter :: new ( stdout_raw ( ) ) ) ) } ,
575556 |mutex| unsafe { mutex. init ( ) } ,
576557 ) ,
577558 }
578559}
579560
561+ pub fn cleanup ( ) {
562+ if let Some ( instance) = STDOUT . get ( ) {
563+ // Flush the data and disable buffering during shutdown
564+ // by replacing the line writer by one with zero
565+ // buffering capacity.
566+ // We use try_lock() instead of lock(), because someone
567+ // might have leaked a StdoutLock, which would
568+ // otherwise cause a deadlock here.
569+ if let Some ( lock) = Pin :: static_ref ( instance) . try_lock ( ) {
570+ * lock. borrow_mut ( ) = LineWriter :: with_capacity ( 0 , stdout_raw ( ) ) ;
571+ }
572+ }
573+ }
574+
580575impl Stdout {
581576 /// Locks this handle to the standard output stream, returning a writable
582577 /// guard.
0 commit comments