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 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.
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() {
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 {
234 self.call_inner(false, &mut |_| f.take().unwrap()());
237 /// Performs the same function as [`call_once`] except ignores poisoning.
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.
247 /// The closure `f` is yielded a [`OnceState`] structure which can be used
248 /// to query the poison status of the `Once`.
250 /// [`call_once`]: struct.Once.html#method.call_once
251 /// [`OnceState`]: struct.OnceState.html
256 /// #![feature(once_poison)]
258 /// use std::sync::Once;
261 /// static INIT: Once = Once::new();
263 /// // poison the once
264 /// let handle = thread::spawn(|| {
265 /// INIT.call_once(|| panic!());
267 /// assert!(handle.join().is_err());
269 /// // poisoning propagates
270 /// let handle = thread::spawn(|| {
271 /// INIT.call_once(|| {});
273 /// assert!(handle.join().is_err());
275 /// // call_once_force will still run and reset the poisoned state
276 /// INIT.call_once_force(|state| {
277 /// assert!(state.poisoned());
280 /// // once any success happens, we stop propagating the poison
281 /// INIT.call_once(|| {});
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 {
295 self.call_inner(true, &mut |p| {
296 f.take().unwrap()(&OnceState { poisoned: p })
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).
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
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.
313 ignore_poisoning: bool,
314 init: &mut dyn FnMut(bool)) {
315 let mut state = self.state.load(Ordering::SeqCst);
319 // If we're complete, then there's nothing to do, we just
320 // jettison out as we shouldn't run the closure.
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");
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
335 let old = self.state.compare_and_swap(state, RUNNING,
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
347 let mut complete = Finish {
351 init(state == POISONED);
352 complete.panicked = false;
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
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(),
368 let me = &mut node as *mut Waiter as usize;
369 assert!(me & STATE_MASK == 0);
371 while state & STATE_MASK == RUNNING {
372 node.next = (state & !STATE_MASK) as *mut Waiter;
373 let old = self.state.compare_and_swap(state,
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) {
387 state = self.state.load(Ordering::SeqCst);
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 {
403 impl<'a> Drop for Finish<'a> {
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)
410 self.me.state.swap(COMPLETE, Ordering::SeqCst)
412 assert_eq!(queue & STATE_MASK, RUNNING);
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.
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);
432 /// Returns whether the associated [`Once`] was poisoned prior to the
433 /// invocation of the closure passed to [`call_once_force`].
435 /// [`call_once_force`]: struct.Once.html#method.call_once_force
436 /// [`Once`]: struct.Once.html
440 /// A poisoned `Once`:
443 /// #![feature(once_poison)]
445 /// use std::sync::Once;
448 /// static INIT: Once = Once::new();
450 /// // poison the once
451 /// let handle = thread::spawn(|| {
452 /// INIT.call_once(|| panic!());
454 /// assert!(handle.join().is_err());
456 /// INIT.call_once_force(|state| {
457 /// assert!(state.poisoned());
461 /// An unpoisoned `Once`:
464 /// #![feature(once_poison)]
466 /// use std::sync::Once;
468 /// static INIT: Once = Once::new();
470 /// INIT.call_once_force(|state| {
471 /// assert!(!state.poisoned());
473 #[unstable(feature = "once_poison", issue = "33577")]
474 pub fn poisoned(&self) -> bool {
479 #[cfg(all(test, not(target_os = "emscripten")))]
482 use sync::mpsc::channel;
488 static O: Once = Once::new();
490 O.call_once(|| a += 1);
492 O.call_once(|| a += 1);
498 static O: Once = Once::new();
499 static mut RUN: bool = false;
501 let (tx, rx) = channel();
504 thread::spawn(move|| {
505 for _ in 0..4 { thread::yield_now() }
513 tx.send(()).unwrap();
532 static O: Once = Once::new();
535 let t = panic::catch_unwind(|| {
536 O.call_once(|| panic!());
540 // poisoning propagates
541 let t = panic::catch_unwind(|| {
546 // we can subvert poisoning, however
547 let mut called = false;
548 O.call_once_force(|p| {
550 assert!(p.poisoned())
554 // once any success happens, we stop propagating the poison
559 fn wait_for_force_to_finish() {
560 static O: Once = Once::new();
563 let t = panic::catch_unwind(|| {
564 O.call_once(|| panic!());
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();
581 // put another waiter on the once
582 let t2 = thread::spawn(|| {
583 let mut called = false;
590 tx2.send(()).unwrap();
592 assert!(t1.join().is_ok());
593 assert!(t2.join().is_ok());