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.
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.
11 //! A "once initialization" primitive
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.
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.
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!
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.
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.
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`:
43 // * Incomplete - no initialization has run yet, and no thread is currently
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
52 // * Complete - initialization has completed and all future calls should finish
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.
62 // You'll find a few more details in the implementation, but that's the gist of
68 use sync::atomic::{AtomicUsize, AtomicBool, Ordering};
69 use thread::{self, Thread};
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.
76 /// [`ONCE_INIT`]: constant.ONCE_INIT.html
77 /// [`Once::new`]: struct.Once.html#method.new
82 /// use std::sync::Once;
84 /// static START: Once = Once::new();
86 /// START.call_once(|| {
87 /// // run initialization here
90 #[stable(feature = "rust1", since = "1.0.0")]
92 // This `state` word is actually an encoded version of just a pointer to a
93 // `Waiter`, so we add the `PhantomData` appropriately.
95 _marker: marker::PhantomData<*mut Waiter>,
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 {}
105 /// State yielded to [`call_once_force`]’s closure parameter. The state can be
106 /// used to query the poison status of the [`Once`].
108 /// [`call_once_force`]: struct.Once.html#method.call_once_force
109 /// [`Once`]: struct.Once.html
110 #[unstable(feature = "once_poison", issue = "33577")]
112 pub struct OnceState {
116 /// Initialization value for static [`Once`] values.
118 /// [`Once`]: struct.Once.html
123 /// use std::sync::{Once, ONCE_INIT};
125 /// static START: Once = ONCE_INIT;
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub const ONCE_INIT: Once = Once::new();
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;
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;
141 // Representation of a node in the linked list of waiters in the RUNNING state.
143 thread: Option<Thread>,
144 signaled: AtomicBool,
148 // Helper struct used to clean up after a closure call with a `Drop`
149 // implementation to also run on panic.
156 /// Creates a new `Once` value.
157 #[stable(feature = "once_new", since = "1.2.0")]
158 pub const fn new() -> Once {
160 state: AtomicUsize::new(INCOMPLETE),
161 _marker: marker::PhantomData,
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.
169 /// This method will block the calling thread if another initialization
170 /// routine is currently running.
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
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.
186 /// use std::sync::Once;
188 /// static mut VAL: usize = 0;
189 /// static INIT: Once = Once::new();
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
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 {
199 /// INIT.call_once(|| {
200 /// VAL = expensive_computation();
206 /// fn expensive_computation() -> usize {
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.
219 /// This is similar to [poisoning with mutexes][poison].
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() {
225 if self.is_completed() {
230 self.call_inner(false, &mut |_| f.take().unwrap()());
233 /// Performs the same function as [`call_once`] except ignores poisoning.
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.
243 /// The closure `f` is yielded a [`OnceState`] structure which can be used
244 /// to query the poison status of the `Once`.
246 /// [`call_once`]: struct.Once.html#method.call_once
247 /// [`OnceState`]: struct.OnceState.html
252 /// #![feature(once_poison)]
254 /// use std::sync::Once;
257 /// static INIT: Once = Once::new();
259 /// // poison the once
260 /// let handle = thread::spawn(|| {
261 /// INIT.call_once(|| panic!());
263 /// assert!(handle.join().is_err());
265 /// // poisoning propagates
266 /// let handle = thread::spawn(|| {
267 /// INIT.call_once(|| {});
269 /// assert!(handle.join().is_err());
271 /// // call_once_force will still run and reset the poisoned state
272 /// INIT.call_once_force(|state| {
273 /// assert!(state.poisoned());
276 /// // once any success happens, we stop propagating the poison
277 /// INIT.call_once(|| {});
279 #[unstable(feature = "once_poison", issue = "33577")]
280 pub fn call_once_force<F>(&self, f: F) where F: FnOnce(&OnceState) {
282 if self.is_completed() {
287 self.call_inner(true, &mut |p| {
288 f.take().unwrap()(&OnceState { poisoned: p })
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
299 /// It is also possible that immediately after `is_completed`
300 /// returns false, some other thread finishes executing
306 /// #![feature(once_is_completed)]
307 /// use std::sync::Once;
309 /// static INIT: Once = Once::new();
311 /// assert_eq!(INIT.is_completed(), false);
312 /// INIT.call_once(|| {
313 /// assert_eq!(INIT.is_completed(), false);
315 /// assert_eq!(INIT.is_completed(), true);
319 /// #![feature(once_is_completed)]
320 /// use std::sync::Once;
323 /// static INIT: Once = Once::new();
325 /// assert_eq!(INIT.is_completed(), false);
326 /// let handle = thread::spawn(|| {
327 /// INIT.call_once(|| panic!());
329 /// assert!(handle.join().is_err());
330 /// assert_eq!(INIT.is_completed(), false);
332 #[unstable(feature = "once_is_completed", issue = "54890")]
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
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).
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
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.
355 ignore_poisoning: bool,
356 init: &mut dyn FnMut(bool)) {
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);
365 // If we're complete, then there's nothing to do, we just
366 // jettison out as we shouldn't run the closure.
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");
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
381 let old = self.state.compare_and_swap(state, RUNNING,
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
393 let mut complete = Finish {
397 init(state == POISONED);
398 complete.panicked = false;
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
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(),
414 let me = &mut node as *mut Waiter as usize;
415 assert!(me & STATE_MASK == 0);
417 while state & STATE_MASK == RUNNING {
418 node.next = (state & !STATE_MASK) as *mut Waiter;
419 let old = self.state.compare_and_swap(state,
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) {
433 state = self.state.load(Ordering::SeqCst);
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 {
449 impl<'a> Drop for Finish<'a> {
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)
456 self.me.state.swap(COMPLETE, Ordering::SeqCst)
458 assert_eq!(queue & STATE_MASK, RUNNING);
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.
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);
478 /// Returns whether the associated [`Once`] was poisoned prior to the
479 /// invocation of the closure passed to [`call_once_force`].
481 /// [`call_once_force`]: struct.Once.html#method.call_once_force
482 /// [`Once`]: struct.Once.html
486 /// A poisoned `Once`:
489 /// #![feature(once_poison)]
491 /// use std::sync::Once;
494 /// static INIT: Once = Once::new();
496 /// // poison the once
497 /// let handle = thread::spawn(|| {
498 /// INIT.call_once(|| panic!());
500 /// assert!(handle.join().is_err());
502 /// INIT.call_once_force(|state| {
503 /// assert!(state.poisoned());
507 /// An unpoisoned `Once`:
510 /// #![feature(once_poison)]
512 /// use std::sync::Once;
514 /// static INIT: Once = Once::new();
516 /// INIT.call_once_force(|state| {
517 /// assert!(!state.poisoned());
519 #[unstable(feature = "once_poison", issue = "33577")]
520 pub fn poisoned(&self) -> bool {
525 #[cfg(all(test, not(target_os = "emscripten")))]
528 use sync::mpsc::channel;
534 static O: Once = Once::new();
536 O.call_once(|| a += 1);
538 O.call_once(|| a += 1);
544 static O: Once = Once::new();
545 static mut RUN: bool = false;
547 let (tx, rx) = channel();
550 thread::spawn(move|| {
551 for _ in 0..4 { thread::yield_now() }
559 tx.send(()).unwrap();
578 static O: Once = Once::new();
581 let t = panic::catch_unwind(|| {
582 O.call_once(|| panic!());
586 // poisoning propagates
587 let t = panic::catch_unwind(|| {
592 // we can subvert poisoning, however
593 let mut called = false;
594 O.call_once_force(|p| {
596 assert!(p.poisoned())
600 // once any success happens, we stop propagating the poison
605 fn wait_for_force_to_finish() {
606 static O: Once = Once::new();
609 let t = panic::catch_unwind(|| {
610 O.call_once(|| panic!());
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();
627 // put another waiter on the once
628 let t2 = thread::spawn(|| {
629 let mut called = false;
636 tx2.send(()).unwrap();
638 assert!(t1.join().is_ok());
639 assert!(t2.join().is_ok());