@@ -30,75 +30,22 @@ use core::pin::Pin;
30
30
/// Used to signal to one of many waiters that the condition they're waiting on has happened.
31
31
pub ( crate ) struct Notifier {
32
32
notify_pending : Mutex < ( bool , Option < Arc < Mutex < FutureState > > > ) > ,
33
- condvar : Condvar ,
34
- }
35
-
36
- macro_rules! check_woken {
37
- ( $guard: expr, $retval: expr) => { {
38
- if $guard. 0 {
39
- $guard. 0 = false ;
40
- if $guard. 1 . as_ref( ) . map( |l| l. lock( ) . unwrap( ) . complete) . unwrap_or( false ) {
41
- // If we're about to return as woken, and the future state is marked complete, wipe
42
- // the future state and let the next future wait until we get a new notify.
43
- $guard. 1 . take( ) ;
44
- }
45
- return $retval;
46
- }
47
- } }
48
33
}
49
34
50
35
impl Notifier {
51
36
pub ( crate ) fn new ( ) -> Self {
52
37
Self {
53
38
notify_pending : Mutex :: new ( ( false , None ) ) ,
54
- condvar : Condvar :: new ( ) ,
55
- }
56
- }
57
-
58
- fn propagate_future_state_to_notify_flag ( & self ) -> MutexGuard < ( bool , Option < Arc < Mutex < FutureState > > > ) > {
59
- let mut lock = self . notify_pending . lock ( ) . unwrap ( ) ;
60
- if let Some ( existing_state) = & lock. 1 {
61
- if existing_state. lock ( ) . unwrap ( ) . callbacks_made {
62
- // If the existing `FutureState` has completed and actually made callbacks,
63
- // consider the notification flag to have been cleared and reset the future state.
64
- lock. 1 . take ( ) ;
65
- lock. 0 = false ;
66
- }
67
39
}
68
- lock
69
40
}
70
41
71
42
pub ( crate ) fn wait ( & self ) {
72
- loop {
73
- let mut guard = self . propagate_future_state_to_notify_flag ( ) ;
74
- check_woken ! ( guard, ( ) ) ;
75
- guard = self . condvar . wait ( guard) . unwrap ( ) ;
76
- check_woken ! ( guard, ( ) ) ;
77
- }
43
+ Sleeper :: from_single_future ( self . get_future ( ) ) . wait ( ) ;
78
44
}
79
45
80
46
#[ cfg( any( test, feature = "std" ) ) ]
81
47
pub ( crate ) fn wait_timeout ( & self , max_wait : Duration ) -> bool {
82
- let current_time = Instant :: now ( ) ;
83
- loop {
84
- let mut guard = self . propagate_future_state_to_notify_flag ( ) ;
85
- check_woken ! ( guard, true ) ;
86
- guard = self . condvar . wait_timeout ( guard, max_wait) . unwrap ( ) . 0 ;
87
- check_woken ! ( guard, true ) ;
88
- // Due to spurious wakeups that can happen on `wait_timeout`, here we need to check if the
89
- // desired wait time has actually passed, and if not then restart the loop with a reduced wait
90
- // time. Note that this logic can be highly simplified through the use of
91
- // `Condvar::wait_while` and `Condvar::wait_timeout_while`, if and when our MSRV is raised to
92
- // 1.42.0.
93
- let elapsed = current_time. elapsed ( ) ;
94
- if elapsed >= max_wait {
95
- return false ;
96
- }
97
- match max_wait. checked_sub ( elapsed) {
98
- None => return false ,
99
- Some ( _) => continue
100
- }
101
- }
48
+ Sleeper :: from_single_future ( self . get_future ( ) ) . wait_timeout ( max_wait)
102
49
}
103
50
104
51
/// Wake waiters, tracking that wake needs to occur even if there are currently no waiters.
@@ -111,13 +58,19 @@ impl Notifier {
111
58
}
112
59
}
113
60
lock. 0 = true ;
114
- mem:: drop ( lock) ;
115
- self . condvar . notify_all ( ) ;
116
61
}
117
62
118
63
/// Gets a [`Future`] that will get woken up with any waiters
119
64
pub ( crate ) fn get_future ( & self ) -> Future {
120
- let mut lock = self . propagate_future_state_to_notify_flag ( ) ;
65
+ let mut lock = self . notify_pending . lock ( ) . unwrap ( ) ;
66
+ if let Some ( existing_state) = & lock. 1 {
67
+ if existing_state. lock ( ) . unwrap ( ) . callbacks_made {
68
+ // If the existing `FutureState` has completed and actually made callbacks,
69
+ // consider the notification flag to have been cleared and reset the future state.
70
+ lock. 1 . take ( ) ;
71
+ lock. 0 = false ;
72
+ }
73
+ }
121
74
if let Some ( existing_state) = & lock. 1 {
122
75
Future { state : Arc :: clone ( & existing_state) }
123
76
} else {
@@ -182,6 +135,9 @@ impl FutureState {
182
135
}
183
136
184
137
/// A simple future which can complete once, and calls some callback(s) when it does so.
138
+ ///
139
+ /// Clones can be made and all futures cloned from the same source will complete at the same time.
140
+ #[ derive( Clone ) ]
185
141
pub struct Future {
186
142
state : Arc < Mutex < FutureState > > ,
187
143
}
@@ -236,6 +192,86 @@ impl<'a> StdFuture for Future {
236
192
}
237
193
}
238
194
195
+ /// A struct which can be used to await multiple [`Future`]s at once without relying on a full
196
+ /// async context.
197
+ pub struct Sleeper {
198
+ notifiers : Vec < Arc < Mutex < FutureState > > > ,
199
+ }
200
+
201
+ impl Sleeper {
202
+ /// Constructs a new sleeper from one future, allowing blocking on it.
203
+ pub fn from_single_future ( future : Future ) -> Self {
204
+ Self { notifiers : vec ! [ future. state] }
205
+ }
206
+ /// Constructs a new sleeper from two futures, allowing blocking on both at once.
207
+ // Note that this is the common case - a ChannelManager and ChainMonitor.
208
+ pub fn from_two_futures ( fut_a : Future , fut_b : Future ) -> Self {
209
+ Self { notifiers : vec ! [ fut_a. state, fut_b. state] }
210
+ }
211
+ /// Constructs a new sleeper on many futures, allowing blocking on all at once.
212
+ pub fn new ( futures : Vec < Future > ) -> Self {
213
+ Self { notifiers : futures. into_iter ( ) . map ( |f| f. state ) . collect ( ) }
214
+ }
215
+ fn setup_wait ( & self ) -> ( Arc < Condvar > , Arc < Mutex < Option < Arc < Mutex < FutureState > > > > > ) {
216
+ let cv = Arc :: new ( Condvar :: new ( ) ) ;
217
+ let notified_fut_mtx = Arc :: new ( Mutex :: new ( None ) ) ;
218
+ {
219
+ for notifier_mtx in self . notifiers . iter ( ) {
220
+ let cv_ref = Arc :: clone ( & cv) ;
221
+ let notified_ref = Arc :: clone ( & notified_fut_mtx) ;
222
+ let notifier_ref = Arc :: clone ( & notifier_mtx) ;
223
+ let mut notifier = notifier_mtx. lock ( ) . unwrap ( ) ;
224
+ if notifier. complete {
225
+ * notified_fut_mtx. lock ( ) . unwrap ( ) = Some ( notifier_ref) ;
226
+ break ;
227
+ }
228
+ notifier. callbacks . push ( ( false , Box :: new ( move || {
229
+ * notified_ref. lock ( ) . unwrap ( ) = Some ( Arc :: clone ( & notifier_ref) ) ;
230
+ cv_ref. notify_all ( ) ;
231
+ } ) ) ) ;
232
+ }
233
+ }
234
+ ( cv, notified_fut_mtx)
235
+ }
236
+
237
+ /// Wait until one of the [`Future`]s registered with this [`Sleeper`] has completed.
238
+ pub fn wait ( & self ) {
239
+ let ( cv, notified_fut_mtx) = self . setup_wait ( ) ;
240
+ let notified_fut = {
241
+ let mut notified_fut_lck = notified_fut_mtx. lock ( ) . unwrap ( ) ;
242
+ loop {
243
+ if let Some ( notified_fut) = notified_fut_lck. take ( ) {
244
+ break notified_fut;
245
+ }
246
+ notified_fut_lck = cv. wait ( notified_fut_lck) . unwrap ( ) ;
247
+ }
248
+ } ;
249
+ notified_fut. lock ( ) . unwrap ( ) . callbacks_made = true ;
250
+ }
251
+
252
+ /// Wait until one of the [`Future`]s registered with this [`Sleeper`] has completed or the
253
+ /// given amount of time has elapsed. Returns true if a [`Future`] completed, false if the time
254
+ /// elapsed.
255
+ #[ cfg( any( test, feature = "std" ) ) ]
256
+ pub fn wait_timeout ( & self , max_wait : Duration ) -> bool {
257
+ let start_time = Instant :: now ( ) ;
258
+ let ( cv, notified_fut_mtx) = self . setup_wait ( ) ;
259
+ let notified_fut = {
260
+ let mut notified_fut_lck = notified_fut_mtx. lock ( ) . unwrap ( ) ;
261
+ loop {
262
+ if let Some ( notified_fut) = notified_fut_lck. take ( ) {
263
+ break notified_fut;
264
+ }
265
+ let sleep_time = max_wait. saturating_sub ( start_time. elapsed ( ) ) ;
266
+ if sleep_time == Duration :: from_secs ( 0 ) { return false ; }
267
+ notified_fut_lck = cv. wait_timeout ( notified_fut_lck, max_wait) . unwrap ( ) . 0 ;
268
+ }
269
+ } ;
270
+ notified_fut. lock ( ) . unwrap ( ) . callbacks_made = true ;
271
+ true
272
+ }
273
+ }
274
+
239
275
#[ cfg( test) ]
240
276
mod tests {
241
277
use super :: * ;
@@ -334,10 +370,7 @@ mod tests {
334
370
let exit_thread_clone = exit_thread. clone ( ) ;
335
371
thread:: spawn ( move || {
336
372
loop {
337
- let mut lock = thread_notifier. notify_pending . lock ( ) . unwrap ( ) ;
338
- lock. 0 = true ;
339
- thread_notifier. condvar . notify_all ( ) ;
340
-
373
+ thread_notifier. notify ( ) ;
341
374
if exit_thread_clone. load ( Ordering :: SeqCst ) {
342
375
break
343
376
}
0 commit comments