@@ -9,8 +9,7 @@ extern crate nix;
9
9
extern crate lazy_static;
10
10
11
11
use nix:: sys:: signal;
12
- use std:: sync:: atomic:: AtomicBool ;
13
- use std:: sync:: atomic:: Ordering :: SeqCst ;
12
+ use std:: sync:: atomic:: { AtomicBool , Ordering } ;
14
13
use std:: time:: Duration ;
15
14
16
15
use std:: { thread, io} ;
@@ -21,17 +20,21 @@ use std::sync::Mutex;
21
20
lazy_static ! {
22
21
// global atomic switch drain control
23
22
static ref ATOMIC_DRAIN_SWITCH : AtomicSwitchCtrl <( ) , io:: Error > = AtomicSwitch :: new(
24
- Discard . map_err( |_| io:: Error :: new( io:: ErrorKind :: Other , "should no happen" ) )
23
+ Discard . map_err( |_| io:: Error :: new( io:: ErrorKind :: Other , "should not happen" ) )
25
24
) . ctrl( ) ;
26
25
27
26
// track current state of the atomic switch drain
28
27
static ref ATOMIC_DRAIN_SWITCH_STATE : AtomicBool = AtomicBool :: new( false ) ;
28
+
29
+ // A flag set by a signal handler to please switch the logger
30
+ // (It can't be switched inside the signal handler, as that would use non async-signal-safe
31
+ // functions).
32
+ static ref SWITCH_SCHEDULED : AtomicBool = AtomicBool :: new( false ) ;
29
33
}
30
34
31
35
fn atomic_drain_switch ( ) {
32
- // XXX: Not atomic. Race?
33
- let new = !ATOMIC_DRAIN_SWITCH_STATE . load ( SeqCst ) ;
34
- ATOMIC_DRAIN_SWITCH_STATE . store ( new, SeqCst ) ;
36
+ // Negate in place and get the new value.
37
+ let new = !ATOMIC_DRAIN_SWITCH_STATE . fetch_nand ( true , Ordering :: Relaxed ) ;
35
38
36
39
if new {
37
40
ATOMIC_DRAIN_SWITCH . set ( Mutex :: new ( slog_json:: Json :: new ( std:: io:: stderr ( ) ) . build ( ) )
@@ -47,7 +50,7 @@ fn atomic_drain_switch() {
47
50
}
48
51
49
52
extern "C" fn handle_sigusr1 ( _: i32 ) {
50
- atomic_drain_switch ( ) ;
53
+ SWITCH_SCHEDULED . store ( true , Ordering :: Relaxed ) ;
51
54
}
52
55
53
56
fn main ( ) {
@@ -71,6 +74,10 @@ fn main() {
71
74
let pid = nix:: unistd:: getpid ( ) ;
72
75
info ! ( log, "kill -SIGUSR1 {}" , pid) ;
73
76
loop {
77
+ if SWITCH_SCHEDULED . swap ( false , Ordering :: Relaxed ) {
78
+ debug ! ( log, "Switching the logger" ) ;
79
+ atomic_drain_switch ( ) ;
80
+ }
74
81
info ! ( log, "tick" ) ;
75
82
thread:: sleep ( Duration :: from_millis ( 3000 ) ) ;
76
83
}
0 commit comments