]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/once.rs
cf9698cb2a9712b6a2439314503c0aef40e63ffd
[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 recursively 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 check
225         if self.is_completed() {
226             return;
227         }
228
229         let mut f = Some(f);
230         self.call_inner(false, &mut |_| f.take().unwrap()());
231     }
232
233     /// Performs the same function as [`call_once`] except ignores poisoning.
234     ///
235     /// Unlike [`call_once`], if this `Once` has been poisoned (i.e. a previous
236     /// call to `call_once` or `call_once_force` caused a panic), calling
237     /// `call_once_force` will still invoke the closure `f` and will _not_
238     /// result in an immediate panic. If `f` panics, the `Once` will remain
239     /// in a poison state. If `f` does _not_ panic, the `Once` will no
240     /// longer be in a poison state and all future calls to `call_once` or
241     /// `call_one_force` will no-op.
242     ///
243     /// The closure `f` is yielded a [`OnceState`] structure which can be used
244     /// to query the poison status of the `Once`.
245     ///
246     /// [`call_once`]: struct.Once.html#method.call_once
247     /// [`OnceState`]: struct.OnceState.html
248     ///
249     /// # Examples
250     ///
251     /// ```
252     /// #![feature(once_poison)]
253     ///
254     /// use std::sync::Once;
255     /// use std::thread;
256     ///
257     /// static INIT: Once = Once::new();
258     ///
259     /// // poison the once
260     /// let handle = thread::spawn(|| {
261     ///     INIT.call_once(|| panic!());
262     /// });
263     /// assert!(handle.join().is_err());
264     ///
265     /// // poisoning propagates
266     /// let handle = thread::spawn(|| {
267     ///     INIT.call_once(|| {});
268     /// });
269     /// assert!(handle.join().is_err());
270     ///
271     /// // call_once_force will still run and reset the poisoned state
272     /// INIT.call_once_force(|state| {
273     ///     assert!(state.poisoned());
274     /// });
275     ///
276     /// // once any success happens, we stop propagating the poison
277     /// INIT.call_once(|| {});
278     /// ```
279     #[unstable(feature = "once_poison", issue = "33577")]
280     pub fn call_once_force<F>(&self, f: F) where F: FnOnce(&OnceState) {
281         // Fast path check
282         if self.is_completed() {
283             return;
284         }
285
286         let mut f = Some(f);
287         self.call_inner(true, &mut |p| {
288             f.take().unwrap()(&OnceState { poisoned: p })
289         });
290     }
291
292     /// Returns true if some `call_once` call has completed
293     /// successfully. Specifically, `is_completed` will return false in
294     /// the following situations:
295     ///   * `call_once` was not called at all,
296     ///   * `call_once` was called, but has not yet completed,
297     ///   * the `Once` instance is poisoned
298     ///
299     /// It is also possible that immediately after `is_completed`
300     /// returns false, some other thread finishes executing
301     /// `call_once`.
302     ///
303     /// # Examples
304     ///
305     /// ```
306     /// #![feature(once_is_completed)]
307     /// use std::sync::Once;
308     ///
309     /// static INIT: Once = Once::new();
310     ///
311     /// assert_eq!(INIT.is_completed(), false);
312     /// INIT.call_once(|| {
313     ///     assert_eq!(INIT.is_completed(), false);
314     /// });
315     /// assert_eq!(INIT.is_completed(), true);
316     /// ```
317     ///
318     /// ```
319     /// #![feature(once_is_completed)]
320     /// use std::sync::Once;
321     /// use std::thread;
322     ///
323     /// static INIT: Once = Once::new();
324     ///
325     /// assert_eq!(INIT.is_completed(), false);
326     /// let handle = thread::spawn(|| {
327     ///     INIT.call_once(|| panic!());
328     /// });
329     /// assert!(handle.join().is_err());
330     /// assert_eq!(INIT.is_completed(), false);
331     /// ```
332     #[unstable(feature = "once_is_completed", issue = "54890")]
333     #[inline]
334     pub fn is_completed(&self) -> bool {
335         // An `Acquire` load is enough because that makes all the initialization
336         // operations visible to us, and, this being a fast path, weaker
337         // ordering helps with performance. This `Acquire` synchronizes with
338         // `SeqCst` operations on the slow path.
339         self.state.load(Ordering::Acquire) == COMPLETE
340     }
341
342     // This is a non-generic function to reduce the monomorphization cost of
343     // using `call_once` (this isn't exactly a trivial or small implementation).
344     //
345     // Additionally, this is tagged with `#[cold]` as it should indeed be cold
346     // and it helps let LLVM know that calls to this function should be off the
347     // fast path. Essentially, this should help generate more straight line code
348     // in LLVM.
349     //
350     // Finally, this takes an `FnMut` instead of a `FnOnce` because there's
351     // currently no way to take an `FnOnce` and call it via virtual dispatch
352     // without some allocation overhead.
353     #[cold]
354     fn call_inner(&self,
355                   ignore_poisoning: bool,
356                   init: &mut dyn FnMut(bool)) {
357
358         // This cold path uses SeqCst consistently because the
359         // performance difference really does not matter there, and
360         // SeqCst minimizes the chances of something going wrong.
361         let mut state = self.state.load(Ordering::SeqCst);
362
363         'outer: loop {
364             match state {
365                 // If we're complete, then there's nothing to do, we just
366                 // jettison out as we shouldn't run the closure.
367                 COMPLETE => return,
368
369                 // If we're poisoned and we're not in a mode to ignore
370                 // poisoning, then we panic here to propagate the poison.
371                 POISONED if !ignore_poisoning => {
372                     panic!("Once instance has previously been poisoned");
373                 }
374
375                 // Otherwise if we see a poisoned or otherwise incomplete state
376                 // we will attempt to move ourselves into the RUNNING state. If
377                 // we succeed, then the queue of waiters starts at null (all 0
378                 // bits).
379                 POISONED |
380                 INCOMPLETE => {
381                     let old = self.state.compare_and_swap(state, RUNNING,
382                                                           Ordering::SeqCst);
383                     if old != state {
384                         state = old;
385                         continue
386                     }
387
388                     // Run the initialization routine, letting it know if we're
389                     // poisoned or not. The `Finish` struct is then dropped, and
390                     // the `Drop` implementation here is responsible for waking
391                     // up other waiters both in the normal return and panicking
392                     // case.
393                     let mut complete = Finish {
394                         panicked: true,
395                         me: self,
396                     };
397                     init(state == POISONED);
398                     complete.panicked = false;
399                     return
400                 }
401
402                 // All other values we find should correspond to the RUNNING
403                 // state with an encoded waiter list in the more significant
404                 // bits. We attempt to enqueue ourselves by moving us to the
405                 // head of the list and bail out if we ever see a state that's
406                 // not RUNNING.
407                 _ => {
408                     assert!(state & STATE_MASK == RUNNING);
409                     let mut node = Waiter {
410                         thread: Some(thread::current()),
411                         signaled: AtomicBool::new(false),
412                         next: ptr::null_mut(),
413                     };
414                     let me = &mut node as *mut Waiter as usize;
415                     assert!(me & STATE_MASK == 0);
416
417                     while state & STATE_MASK == RUNNING {
418                         node.next = (state & !STATE_MASK) as *mut Waiter;
419                         let old = self.state.compare_and_swap(state,
420                                                               me | RUNNING,
421                                                               Ordering::SeqCst);
422                         if old != state {
423                             state = old;
424                             continue
425                         }
426
427                         // Once we've enqueued ourselves, wait in a loop.
428                         // Afterwards reload the state and continue with what we
429                         // were doing from before.
430                         while !node.signaled.load(Ordering::SeqCst) {
431                             thread::park();
432                         }
433                         state = self.state.load(Ordering::SeqCst);
434                         continue 'outer
435                     }
436                 }
437             }
438         }
439     }
440 }
441
442 #[stable(feature = "std_debug", since = "1.16.0")]
443 impl fmt::Debug for Once {
444     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
445         f.pad("Once { .. }")
446     }
447 }
448
449 impl<'a> Drop for Finish<'a> {
450     fn drop(&mut self) {
451         // Swap out our state with however we finished. We should only ever see
452         // an old state which was RUNNING.
453         let queue = if self.panicked {
454             self.me.state.swap(POISONED, Ordering::SeqCst)
455         } else {
456             self.me.state.swap(COMPLETE, Ordering::SeqCst)
457         };
458         assert_eq!(queue & STATE_MASK, RUNNING);
459
460         // Decode the RUNNING to a list of waiters, then walk that entire list
461         // and wake them up. Note that it is crucial that after we store `true`
462         // in the node it can be free'd! As a result we load the `thread` to
463         // signal ahead of time and then unpark it after the store.
464         unsafe {
465             let mut queue = (queue & !STATE_MASK) as *mut Waiter;
466             while !queue.is_null() {
467                 let next = (*queue).next;
468                 let thread = (*queue).thread.take().unwrap();
469                 (*queue).signaled.store(true, Ordering::SeqCst);
470                 thread.unpark();
471                 queue = next;
472             }
473         }
474     }
475 }
476
477 impl OnceState {
478     /// Returns whether the associated [`Once`] was poisoned prior to the
479     /// invocation of the closure passed to [`call_once_force`].
480     ///
481     /// [`call_once_force`]: struct.Once.html#method.call_once_force
482     /// [`Once`]: struct.Once.html
483     ///
484     /// # Examples
485     ///
486     /// A poisoned `Once`:
487     ///
488     /// ```
489     /// #![feature(once_poison)]
490     ///
491     /// use std::sync::Once;
492     /// use std::thread;
493     ///
494     /// static INIT: Once = Once::new();
495     ///
496     /// // poison the once
497     /// let handle = thread::spawn(|| {
498     ///     INIT.call_once(|| panic!());
499     /// });
500     /// assert!(handle.join().is_err());
501     ///
502     /// INIT.call_once_force(|state| {
503     ///     assert!(state.poisoned());
504     /// });
505     /// ```
506     ///
507     /// An unpoisoned `Once`:
508     ///
509     /// ```
510     /// #![feature(once_poison)]
511     ///
512     /// use std::sync::Once;
513     ///
514     /// static INIT: Once = Once::new();
515     ///
516     /// INIT.call_once_force(|state| {
517     ///     assert!(!state.poisoned());
518     /// });
519     #[unstable(feature = "once_poison", issue = "33577")]
520     pub fn poisoned(&self) -> bool {
521         self.poisoned
522     }
523 }
524
525 #[cfg(all(test, not(target_os = "emscripten")))]
526 mod tests {
527     use panic;
528     use sync::mpsc::channel;
529     use thread;
530     use super::Once;
531
532     #[test]
533     fn smoke_once() {
534         static O: Once = Once::new();
535         let mut a = 0;
536         O.call_once(|| a += 1);
537         assert_eq!(a, 1);
538         O.call_once(|| a += 1);
539         assert_eq!(a, 1);
540     }
541
542     #[test]
543     fn stampede_once() {
544         static O: Once = Once::new();
545         static mut RUN: bool = false;
546
547         let (tx, rx) = channel();
548         for _ in 0..10 {
549             let tx = tx.clone();
550             thread::spawn(move|| {
551                 for _ in 0..4 { thread::yield_now() }
552                 unsafe {
553                     O.call_once(|| {
554                         assert!(!RUN);
555                         RUN = true;
556                     });
557                     assert!(RUN);
558                 }
559                 tx.send(()).unwrap();
560             });
561         }
562
563         unsafe {
564             O.call_once(|| {
565                 assert!(!RUN);
566                 RUN = true;
567             });
568             assert!(RUN);
569         }
570
571         for _ in 0..10 {
572             rx.recv().unwrap();
573         }
574     }
575
576     #[test]
577     fn poison_bad() {
578         static O: Once = Once::new();
579
580         // poison the once
581         let t = panic::catch_unwind(|| {
582             O.call_once(|| panic!());
583         });
584         assert!(t.is_err());
585
586         // poisoning propagates
587         let t = panic::catch_unwind(|| {
588             O.call_once(|| {});
589         });
590         assert!(t.is_err());
591
592         // we can subvert poisoning, however
593         let mut called = false;
594         O.call_once_force(|p| {
595             called = true;
596             assert!(p.poisoned())
597         });
598         assert!(called);
599
600         // once any success happens, we stop propagating the poison
601         O.call_once(|| {});
602     }
603
604     #[test]
605     fn wait_for_force_to_finish() {
606         static O: Once = Once::new();
607
608         // poison the once
609         let t = panic::catch_unwind(|| {
610             O.call_once(|| panic!());
611         });
612         assert!(t.is_err());
613
614         // make sure someone's waiting inside the once via a force
615         let (tx1, rx1) = channel();
616         let (tx2, rx2) = channel();
617         let t1 = thread::spawn(move || {
618             O.call_once_force(|p| {
619                 assert!(p.poisoned());
620                 tx1.send(()).unwrap();
621                 rx2.recv().unwrap();
622             });
623         });
624
625         rx1.recv().unwrap();
626
627         // put another waiter on the once
628         let t2 = thread::spawn(|| {
629             let mut called = false;
630             O.call_once(|| {
631                 called = true;
632             });
633             assert!(!called);
634         });
635
636         tx2.send(()).unwrap();
637
638         assert!(t1.join().is_ok());
639         assert!(t2.join().is_ok());
640
641     }
642 }