@@ -16,8 +16,6 @@ use crate::sys_common;
16
16
use crate :: sys_common:: remutex:: { ReentrantMutex , ReentrantMutexGuard } ;
17
17
use crate :: thread:: LocalKey ;
18
18
19
- static LOCAL_STREAMS : AtomicBool = AtomicBool :: new ( false ) ;
20
-
21
19
thread_local ! {
22
20
/// Used by the test crate to capture the output of the print! and println! macros.
23
21
static LOCAL_STDOUT : RefCell <Option <Box <dyn Write + Send >>> = {
@@ -32,6 +30,20 @@ thread_local! {
32
30
}
33
31
}
34
32
33
+ /// Flag to indicate LOCAL_STDOUT and/or LOCAL_STDERR is used.
34
+ ///
35
+ /// If both are None and were never set on any thread, this flag is set to
36
+ /// false, and both LOCAL_STDOUT and LOCAL_STDOUT can be safely ignored on all
37
+ /// threads, saving some time and memory registering an unused thread local.
38
+ ///
39
+ /// Note about memory ordering: This contains information about whether two
40
+ /// thread local variables might be in use. Although this is a global flag, the
41
+ /// memory ordering between threads does not matter: we only want this flag to
42
+ /// have a consistent order between set_print/set_panic and print_to *within
43
+ /// the same thread*. Within the same thread, things always have a perfectly
44
+ /// consistent order. So Ordering::Relaxed is fine.
45
+ static LOCAL_STREAMS : AtomicBool = AtomicBool :: new ( false ) ;
46
+
35
47
/// A handle to a raw instance of the standard input stream of this process.
36
48
///
37
49
/// This handle is not synchronized or buffered in any fashion. Constructed via
@@ -899,7 +911,7 @@ pub fn set_panic(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write +
899
911
Some ( s)
900
912
} ,
901
913
) ;
902
- LOCAL_STREAMS . store ( true , Ordering :: Release ) ;
914
+ LOCAL_STREAMS . store ( true , Ordering :: Relaxed ) ;
903
915
s
904
916
}
905
917
@@ -926,7 +938,7 @@ pub fn set_print(sink: Option<Box<dyn Write + Send>>) -> Option<Box<dyn Write +
926
938
Some ( s)
927
939
} ,
928
940
) ;
929
- LOCAL_STREAMS . store ( true , Ordering :: Release ) ;
941
+ LOCAL_STREAMS . store ( true , Ordering :: Relaxed ) ;
930
942
s
931
943
}
932
944
@@ -949,7 +961,7 @@ fn print_to<T>(
949
961
T : Write ,
950
962
{
951
963
let result = LOCAL_STREAMS
952
- . load ( Ordering :: Acquire )
964
+ . load ( Ordering :: Relaxed )
953
965
. then ( || {
954
966
local_s
955
967
. try_with ( |s| {
0 commit comments