]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/once.rs
Rollup merge of #53110 - Xanewok:save-analysis-remap-path, r=nrc
[rust.git] / src / libstd / sync / once.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! A "once initialization" primitive
12 //!
13 //! This primitive is meant to be used to run one-time initialization. An
14 //! example use case would be for initializing an FFI library.
15
16 // A "once" is a relatively simple primitive, and it's also typically provided
17 // by the OS as well (see `pthread_once` or `InitOnceExecuteOnce`). The OS
18 // primitives, however, tend to have surprising restrictions, such as the Unix
19 // one doesn't allow an argument to be passed to the function.
20 //
21 // As a result, we end up implementing it ourselves in the standard library.
22 // This also gives us the opportunity to optimize the implementation a bit which
23 // should help the fast path on call sites. Consequently, let's explain how this
24 // primitive works now!
25 //
26 // So to recap, the guarantees of a Once are that it will call the
27 // initialization closure at most once, and it will never return until the one
28 // that's running has finished running. This means that we need some form of
29 // blocking here while the custom callback is running at the very least.
30 // Additionally, we add on the restriction of **poisoning**. Whenever an
31 // initialization closure panics, the Once enters a "poisoned" state which means
32 // that all future calls will immediately panic as well.
33 //
34 // So to implement this, one might first reach for a `Mutex`, but those cannot
35 // be put into a `static`. It also gets a lot harder with poisoning to figure
36 // out when the mutex needs to be deallocated because it's not after the closure
37 // finishes, but after the first successful closure finishes.
38 //
39 // All in all, this is instead implemented with atomics and lock-free
40 // operations! Whee! Each `Once` has one word of atomic state, and this state is
41 // CAS'd on to determine what to do. There are four possible state of a `Once`:
42 //
43 // * Incomplete - no initialization has run yet, and no thread is currently
44 //                using the Once.
45 // * Poisoned - some thread has previously attempted to initialize the Once, but
46 //              it panicked, so the Once is now poisoned. There are no other
47 //              threads currently accessing this Once.
48 // * Running - some thread is currently attempting to run initialization. It may
49 //             succeed, so all future threads need to wait for it to finish.
50 //             Note that this state is accompanied with a payload, described
51 //             below.
52 // * Complete - initialization has completed and all future calls should finish
53 //              immediately.
54 //
55 // With 4 states we need 2 bits to encode this, and we use the remaining bits
56 // in the word we have allocated as a queue of threads waiting for the thread
57 // responsible for entering the RUNNING state. This queue is just a linked list
58 // of Waiter nodes which is monotonically increasing in size. Each node is
59 // allocated on the stack, and whenever the running closure finishes it will
60 // consume the entire queue and notify all waiters they should try again.
61 //
62 // You'll find a few more details in the implementation, but that's the gist of
63 // it!
64
65 use fmt;
66 use marker;
67 use ptr;
68 use sync::atomic::{AtomicUsize, AtomicBool, Ordering};
69 use thread::{self, Thread};
70
71 /// A synchronization primitive which can be used to run a one-time global
72 /// initialization. Useful for one-time initialization for FFI or related
73 /// functionality. This type can only be constructed with the [`ONCE_INIT`]
74 /// value or the equivalent [`Once::new`] constructor.
75 ///
76 /// [`ONCE_INIT`]: constant.ONCE_INIT.html
77 /// [`Once::new`]: struct.Once.html#method.new
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// use std::sync::Once;
83 ///
84 /// static START: Once = Once::new();
85 ///
86 /// START.call_once(|| {
87 ///     // run initialization here
88 /// });
89 /// ```
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub struct Once {
92     // This `state` word is actually an encoded version of just a pointer to a
93     // `Waiter`, so we add the `PhantomData` appropriately.
94     state: AtomicUsize,
95     _marker: marker::PhantomData<*mut Waiter>,
96 }
97
98 // The `PhantomData` of a raw pointer removes these two auto traits, but we
99 // enforce both below in the implementation so this should be safe to add.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 unsafe impl Sync for Once {}
102 #[stable(feature = "rust1", since = "1.0.0")]
103 unsafe impl Send for Once {}
104
105 /// State yielded to [`call_once_force`]’s closure parameter. The state can be
106 /// used to query the poison status of the [`Once`].
107 ///
108 /// [`call_once_force`]: struct.Once.html#method.call_once_force
109 /// [`Once`]: struct.Once.html
110 #[unstable(feature = "once_poison", issue = "33577")]
111 #[derive(Debug)]
112 pub struct OnceState {
113     poisoned: bool,
114 }
115
116 /// Initialization value for static [`Once`] values.
117 ///
118 /// [`Once`]: struct.Once.html
119 ///
120 /// # Examples
121 ///
122 /// ```
123 /// use std::sync::{Once, ONCE_INIT};
124 ///
125 /// static START: Once = ONCE_INIT;
126 /// ```
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub const ONCE_INIT: Once = Once::new();
129
130 // Four states that a Once can be in, encoded into the lower bits of `state` in
131 // the Once structure.
132 const INCOMPLETE: usize = 0x0;
133 const POISONED: usize = 0x1;
134 const RUNNING: usize = 0x2;
135 const COMPLETE: usize = 0x3;
136
137 // Mask to learn about the state. All other bits are the queue of waiters if
138 // this is in the RUNNING state.
139 const STATE_MASK: usize = 0x3;
140
141 // Representation of a node in the linked list of waiters in the RUNNING state.
142 struct Waiter {
143     thread: Option<Thread>,
144     signaled: AtomicBool,
145     next: *mut Waiter,
146 }
147
148 // Helper struct used to clean up after a closure call with a `Drop`
149 // implementation to also run on panic.
150 struct Finish<'a> {
151     panicked: bool,
152     me: &'a Once,
153 }
154
155 impl Once {
156     /// Creates a new `Once` value.
157     #[stable(feature = "once_new", since = "1.2.0")]
158     pub const fn new() -> Once {
159         Once {
160             state: AtomicUsize::new(INCOMPLETE),
161             _marker: marker::PhantomData,
162         }
163     }
164
165     /// Performs an initialization routine once and only once. The given closure
166     /// will be executed if this is the first time `call_once` has been called,
167     /// and otherwise the routine will *not* be invoked.
168     ///
169     /// This method will block the calling thread if another initialization
170     /// routine is currently running.
171     ///
172     /// When this function returns, it is guaranteed that some initialization
173     /// has run and completed (it may not be the closure specified). It is also
174     /// guaranteed that any memory writes performed by the executed closure can
175     /// be reliably observed by other threads at this point (there is a
176     /// happens-before relation between the closure and code executing after the
177     /// return).
178     ///
179     /// If the given closure recusively invokes `call_once` on the same `Once`
180     /// instance the exact behavior is not specified, allowed outcomes are
181     /// a panic or a deadlock.
182     ///
183     /// # Examples
184     ///
185     /// ```
186     /// use std::sync::Once;
187     ///
188     /// static mut VAL: usize = 0;
189     /// static INIT: Once = Once::new();
190     ///
191     /// // Accessing a `static mut` is unsafe much of the time, but if we do so
192     /// // in a synchronized fashion (e.g. write once or read all) then we're
193     /// // good to go!
194     /// //
195     /// // This function will only call `expensive_computation` once, and will
196     /// // otherwise always return the value returned from the first invocation.
197     /// fn get_cached_val() -> usize {
198     ///     unsafe {
199     ///         INIT.call_once(|| {
200     ///             VAL = expensive_computation();
201     ///         });
202     ///         VAL
203     ///     }
204     /// }
205     ///
206     /// fn expensive_computation() -> usize {
207     ///     // ...
208     /// # 2
209     /// }
210     /// ```
211     ///
212     /// # Panics
213     ///
214     /// The closure `f` will only be executed once if this is called
215     /// concurrently amongst many threads. If that closure panics, however, then
216     /// it will *poison* this `Once` instance, causing all future invocations of
217     /// `call_once` to also panic.
218     ///
219     /// This is similar to [poisoning with mutexes][poison].
220     ///
221     /// [poison]: struct.Mutex.html#poisoning
222     #[stable(feature = "rust1", since = "1.0.0")]
223     pub fn call_once<F>(&self, f: F) where F: FnOnce() {
224         // Fast path, just see if we've completed initialization.
225         // An `Acquire` load is enough because that makes all the initialization
226         // operations visible to us. The cold path uses SeqCst consistently
227         // because the performance difference really does not matter there,
228         // and SeqCst minimizes the chances of something going wrong.
229         if self.state.load(Ordering::Acquire) == COMPLETE {
230             return
231         }
232
233         let mut f = Some(f);
234         self.call_inner(false, &mut |_| f.take().unwrap()());
235     }
236
237     /// Performs the same function as [`call_once`] except ignores poisoning.
238     ///
239     /// Unlike [`call_once`], if this `Once` has been poisoned (i.e. a previous
240     /// call to `call_once` or `call_once_force` caused a panic), calling
241     /// `call_once_force` will still invoke the closure `f` and will _not_
242     /// result in an immediate panic. If `f` panics, the `Once` will remain
243     /// in a poison state. If `f` does _not_ panic, the `Once` will no
244     /// longer be in a poison state and all future calls to `call_once` or
245     /// `call_one_force` will no-op.
246     ///
247     /// The closure `f` is yielded a [`OnceState`] structure which can be used
248     /// to query the poison status of the `Once`.
249     ///
250     /// [`call_once`]: struct.Once.html#method.call_once
251     /// [`OnceState`]: struct.OnceState.html
252     ///
253     /// # Examples
254     ///
255     /// ```
256     /// #![feature(once_poison)]
257     ///
258     /// use std::sync::Once;
259     /// use std::thread;
260     ///
261     /// static INIT: Once = Once::new();
262     ///
263     /// // poison the once
264     /// let handle = thread::spawn(|| {
265     ///     INIT.call_once(|| panic!());
266     /// });
267     /// assert!(handle.join().is_err());
268     ///
269     /// // poisoning propagates
270     /// let handle = thread::spawn(|| {
271     ///     INIT.call_once(|| {});
272     /// });
273     /// assert!(handle.join().is_err());
274     ///
275     /// // call_once_force will still run and reset the poisoned state
276     /// INIT.call_once_force(|state| {
277     ///     assert!(state.poisoned());
278     /// });
279     ///
280     /// // once any success happens, we stop propagating the poison
281     /// INIT.call_once(|| {});
282     /// ```
283     #[unstable(feature = "once_poison", issue = "33577")]
284     pub fn call_once_force<F>(&self, f: F) where F: FnOnce(&OnceState) {
285         // same as above, just with a different parameter to `call_inner`.
286         // An `Acquire` load is enough because that makes all the initialization
287         // operations visible to us. The cold path uses SeqCst consistently
288         // because the performance difference really does not matter there,
289         // and SeqCst minimizes the chances of something going wrong.
290         if self.state.load(Ordering::Acquire) == COMPLETE {
291             return
292         }
293
294         let mut f = Some(f);
295         self.call_inner(true, &mut |p| {
296             f.take().unwrap()(&OnceState { poisoned: p })
297         });
298     }
299
300     // This is a non-generic function to reduce the monomorphization cost of
301     // using `call_once` (this isn't exactly a trivial or small implementation).
302     //
303     // Additionally, this is tagged with `#[cold]` as it should indeed be cold
304     // and it helps let LLVM know that calls to this function should be off the
305     // fast path. Essentially, this should help generate more straight line code
306     // in LLVM.
307     //
308     // Finally, this takes an `FnMut` instead of a `FnOnce` because there's
309     // currently no way to take an `FnOnce` and call it via virtual dispatch
310     // without some allocation overhead.
311     #[cold]
312     fn call_inner(&self,
313                   ignore_poisoning: bool,
314                   init: &mut dyn FnMut(bool)) {
315         let mut state = self.state.load(Ordering::SeqCst);
316
317         'outer: loop {
318             match state {
319                 // If we're complete, then there's nothing to do, we just
320                 // jettison out as we shouldn't run the closure.
321                 COMPLETE => return,
322
323                 // If we're poisoned and we're not in a mode to ignore
324                 // poisoning, then we panic here to propagate the poison.
325                 POISONED if !ignore_poisoning => {
326                     panic!("Once instance has previously been poisoned");
327                 }
328
329                 // Otherwise if we see a poisoned or otherwise incomplete state
330                 // we will attempt to move ourselves into the RUNNING state. If
331                 // we succeed, then the queue of waiters starts at null (all 0
332                 // bits).
333                 POISONED |
334                 INCOMPLETE => {
335                     let old = self.state.compare_and_swap(state, RUNNING,
336                                                           Ordering::SeqCst);
337                     if old != state {
338                         state = old;
339                         continue
340                     }
341
342                     // Run the initialization routine, letting it know if we're
343                     // poisoned or not. The `Finish` struct is then dropped, and
344                     // the `Drop` implementation here is responsible for waking
345                     // up other waiters both in the normal return and panicking
346                     // case.
347                     let mut complete = Finish {
348                         panicked: true,
349                         me: self,
350                     };
351                     init(state == POISONED);
352                     complete.panicked = false;
353                     return
354                 }
355
356                 // All other values we find should correspond to the RUNNING
357                 // state with an encoded waiter list in the more significant
358                 // bits. We attempt to enqueue ourselves by moving us to the
359                 // head of the list and bail out if we ever see a state that's
360                 // not RUNNING.
361                 _ => {
362                     assert!(state & STATE_MASK == RUNNING);
363                     let mut node = Waiter {
364                         thread: Some(thread::current()),
365                         signaled: AtomicBool::new(false),
366                         next: ptr::null_mut(),
367                     };
368                     let me = &mut node as *mut Waiter as usize;
369                     assert!(me & STATE_MASK == 0);
370
371                     while state & STATE_MASK == RUNNING {
372                         node.next = (state & !STATE_MASK) as *mut Waiter;
373                         let old = self.state.compare_and_swap(state,
374                                                               me | RUNNING,
375                                                               Ordering::SeqCst);
376                         if old != state {
377                             state = old;
378                             continue
379                         }
380
381                         // Once we've enqueued ourselves, wait in a loop.
382                         // Afterwards reload the state and continue with what we
383                         // were doing from before.
384                         while !node.signaled.load(Ordering::SeqCst) {
385                             thread::park();
386                         }
387                         state = self.state.load(Ordering::SeqCst);
388                         continue 'outer
389                     }
390                 }
391             }
392         }
393     }
394 }
395
396 #[stable(feature = "std_debug", since = "1.16.0")]
397 impl fmt::Debug for Once {
398     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399         f.pad("Once { .. }")
400     }
401 }
402
403 impl<'a> Drop for Finish<'a> {
404     fn drop(&mut self) {
405         // Swap out our state with however we finished. We should only ever see
406         // an old state which was RUNNING.
407         let queue = if self.panicked {
408             self.me.state.swap(POISONED, Ordering::SeqCst)
409         } else {
410             self.me.state.swap(COMPLETE, Ordering::SeqCst)
411         };
412         assert_eq!(queue & STATE_MASK, RUNNING);
413
414         // Decode the RUNNING to a list of waiters, then walk that entire list
415         // and wake them up. Note that it is crucial that after we store `true`
416         // in the node it can be free'd! As a result we load the `thread` to
417         // signal ahead of time and then unpark it after the store.
418         unsafe {
419             let mut queue = (queue & !STATE_MASK) as *mut Waiter;
420             while !queue.is_null() {
421                 let next = (*queue).next;
422                 let thread = (*queue).thread.take().unwrap();
423                 (*queue).signaled.store(true, Ordering::SeqCst);
424                 thread.unpark();
425                 queue = next;
426             }
427         }
428     }
429 }
430
431 impl OnceState {
432     /// Returns whether the associated [`Once`] was poisoned prior to the
433     /// invocation of the closure passed to [`call_once_force`].
434     ///
435     /// [`call_once_force`]: struct.Once.html#method.call_once_force
436     /// [`Once`]: struct.Once.html
437     ///
438     /// # Examples
439     ///
440     /// A poisoned `Once`:
441     ///
442     /// ```
443     /// #![feature(once_poison)]
444     ///
445     /// use std::sync::Once;
446     /// use std::thread;
447     ///
448     /// static INIT: Once = Once::new();
449     ///
450     /// // poison the once
451     /// let handle = thread::spawn(|| {
452     ///     INIT.call_once(|| panic!());
453     /// });
454     /// assert!(handle.join().is_err());
455     ///
456     /// INIT.call_once_force(|state| {
457     ///     assert!(state.poisoned());
458     /// });
459     /// ```
460     ///
461     /// An unpoisoned `Once`:
462     ///
463     /// ```
464     /// #![feature(once_poison)]
465     ///
466     /// use std::sync::Once;
467     ///
468     /// static INIT: Once = Once::new();
469     ///
470     /// INIT.call_once_force(|state| {
471     ///     assert!(!state.poisoned());
472     /// });
473     #[unstable(feature = "once_poison", issue = "33577")]
474     pub fn poisoned(&self) -> bool {
475         self.poisoned
476     }
477 }
478
479 #[cfg(all(test, not(target_os = "emscripten")))]
480 mod tests {
481     use panic;
482     use sync::mpsc::channel;
483     use thread;
484     use super::Once;
485
486     #[test]
487     fn smoke_once() {
488         static O: Once = Once::new();
489         let mut a = 0;
490         O.call_once(|| a += 1);
491         assert_eq!(a, 1);
492         O.call_once(|| a += 1);
493         assert_eq!(a, 1);
494     }
495
496     #[test]
497     fn stampede_once() {
498         static O: Once = Once::new();
499         static mut RUN: bool = false;
500
501         let (tx, rx) = channel();
502         for _ in 0..10 {
503             let tx = tx.clone();
504             thread::spawn(move|| {
505                 for _ in 0..4 { thread::yield_now() }
506                 unsafe {
507                     O.call_once(|| {
508                         assert!(!RUN);
509                         RUN = true;
510                     });
511                     assert!(RUN);
512                 }
513                 tx.send(()).unwrap();
514             });
515         }
516
517         unsafe {
518             O.call_once(|| {
519                 assert!(!RUN);
520                 RUN = true;
521             });
522             assert!(RUN);
523         }
524
525         for _ in 0..10 {
526             rx.recv().unwrap();
527         }
528     }
529
530     #[test]
531     fn poison_bad() {
532         static O: Once = Once::new();
533
534         // poison the once
535         let t = panic::catch_unwind(|| {
536             O.call_once(|| panic!());
537         });
538         assert!(t.is_err());
539
540         // poisoning propagates
541         let t = panic::catch_unwind(|| {
542             O.call_once(|| {});
543         });
544         assert!(t.is_err());
545
546         // we can subvert poisoning, however
547         let mut called = false;
548         O.call_once_force(|p| {
549             called = true;
550             assert!(p.poisoned())
551         });
552         assert!(called);
553
554         // once any success happens, we stop propagating the poison
555         O.call_once(|| {});
556     }
557
558     #[test]
559     fn wait_for_force_to_finish() {
560         static O: Once = Once::new();
561
562         // poison the once
563         let t = panic::catch_unwind(|| {
564             O.call_once(|| panic!());
565         });
566         assert!(t.is_err());
567
568         // make sure someone's waiting inside the once via a force
569         let (tx1, rx1) = channel();
570         let (tx2, rx2) = channel();
571         let t1 = thread::spawn(move || {
572             O.call_once_force(|p| {
573                 assert!(p.poisoned());
574                 tx1.send(()).unwrap();
575                 rx2.recv().unwrap();
576             });
577         });
578
579         rx1.recv().unwrap();
580
581         // put another waiter on the once
582         let t2 = thread::spawn(|| {
583             let mut called = false;
584             O.call_once(|| {
585                 called = true;
586             });
587             assert!(!called);
588         });
589
590         tx2.send(()).unwrap();
591
592         assert!(t1.join().is_ok());
593         assert!(t2.join().is_ok());
594
595     }
596 }