1 //! A "once initialization" primitive
3 //! This primitive is meant to be used to run one-time initialization. An
4 //! example use case would be for initializing an FFI library.
6 // A "once" is a relatively simple primitive, and it's also typically provided
7 // by the OS as well (see `pthread_once` or `InitOnceExecuteOnce`). The OS
8 // primitives, however, tend to have surprising restrictions, such as the Unix
9 // one doesn't allow an argument to be passed to the function.
11 // As a result, we end up implementing it ourselves in the standard library.
12 // This also gives us the opportunity to optimize the implementation a bit which
13 // should help the fast path on call sites. Consequently, let's explain how this
14 // primitive works now!
16 // So to recap, the guarantees of a Once are that it will call the
17 // initialization closure at most once, and it will never return until the one
18 // that's running has finished running. This means that we need some form of
19 // blocking here while the custom callback is running at the very least.
20 // Additionally, we add on the restriction of **poisoning**. Whenever an
21 // initialization closure panics, the Once enters a "poisoned" state which means
22 // that all future calls will immediately panic as well.
24 // So to implement this, one might first reach for a `Mutex`, but those cannot
25 // be put into a `static`. It also gets a lot harder with poisoning to figure
26 // out when the mutex needs to be deallocated because it's not after the closure
27 // finishes, but after the first successful closure finishes.
29 // All in all, this is instead implemented with atomics and lock-free
30 // operations! Whee! Each `Once` has one word of atomic state, and this state is
31 // CAS'd on to determine what to do. There are four possible state of a `Once`:
33 // * Incomplete - no initialization has run yet, and no thread is currently
35 // * Poisoned - some thread has previously attempted to initialize the Once, but
36 // it panicked, so the Once is now poisoned. There are no other
37 // threads currently accessing this Once.
38 // * Running - some thread is currently attempting to run initialization. It may
39 // succeed, so all future threads need to wait for it to finish.
40 // Note that this state is accompanied with a payload, described
42 // * Complete - initialization has completed and all future calls should finish
45 // With 4 states we need 2 bits to encode this, and we use the remaining bits
46 // in the word we have allocated as a queue of threads waiting for the thread
47 // responsible for entering the RUNNING state. This queue is just a linked list
48 // of Waiter nodes which is monotonically increasing in size. Each node is
49 // allocated on the stack, and whenever the running closure finishes it will
50 // consume the entire queue and notify all waiters they should try again.
52 // You'll find a few more details in the implementation, but that's the gist of
56 // When running `Once` we deal with multiple atomics:
57 // `Once.state_and_queue` and an unknown number of `Waiter.signaled`.
58 // * `state_and_queue` is used (1) as a state flag, (2) for synchronizing the
59 // result of the `Once`, and (3) for synchronizing `Waiter` nodes.
60 // - At the end of the `call_inner` function we have to make sure the result
61 // of the `Once` is acquired. So every load which can be the only one to
62 // load COMPLETED must have at least Acquire ordering, which means all
64 // - `WaiterQueue::Drop` is the only place that may store COMPLETED, and
65 // must do so with Release ordering to make the result available.
66 // - `wait` inserts `Waiter` nodes as a pointer in `state_and_queue`, and
67 // needs to make the nodes available with Release ordering. The load in
68 // its `compare_exchange` can be Relaxed because it only has to compare
69 // the atomic, not to read other data.
70 // - `WaiterQueue::Drop` must see the `Waiter` nodes, so it must load
71 // `state_and_queue` with Acquire ordering.
72 // - There is just one store where `state_and_queue` is used only as a
73 // state flag, without having to synchronize data: switching the state
74 // from INCOMPLETE to RUNNING in `call_inner`. This store can be Relaxed,
75 // but the read has to be Acquire because of the requirements mentioned
77 // * `Waiter.signaled` is both used as a flag, and to protect a field with
78 // interior mutability in `Waiter`. `Waiter.thread` is changed in
79 // `WaiterQueue::Drop` which then sets `signaled` with Release ordering.
80 // After `wait` loads `signaled` with Acquire and sees it is true, it needs to
81 // see the changes to drop the `Waiter` struct correctly.
82 // * There is one place where the two atomics `Once.state_and_queue` and
83 // `Waiter.signaled` come together, and might be reordered by the compiler or
84 // processor. Because both use Acquire ordering such a reordering is not
85 // allowed, so no need for SeqCst.
87 #[cfg(all(test, not(target_os = "emscripten")))]
90 use crate::cell::Cell;
93 use crate::panic::{RefUnwindSafe, UnwindSafe};
94 use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
95 use crate::thread::{self, Thread};
97 /// A synchronization primitive which can be used to run a one-time global
98 /// initialization. Useful for one-time initialization for FFI or related
99 /// functionality. This type can only be constructed with [`Once::new()`].
104 /// use std::sync::Once;
106 /// static START: Once = Once::new();
108 /// START.call_once(|| {
109 /// // run initialization here
112 #[stable(feature = "rust1", since = "1.0.0")]
114 // `state_and_queue` is actually a pointer to a `Waiter` with extra state
115 // bits, so we add the `PhantomData` appropriately.
116 state_and_queue: AtomicUsize,
117 _marker: marker::PhantomData<*const Waiter>,
120 // The `PhantomData` of a raw pointer removes these two auto traits, but we
121 // enforce both below in the implementation so this should be safe to add.
122 #[stable(feature = "rust1", since = "1.0.0")]
123 unsafe impl Sync for Once {}
124 #[stable(feature = "rust1", since = "1.0.0")]
125 unsafe impl Send for Once {}
127 #[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
128 impl UnwindSafe for Once {}
130 #[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
131 impl RefUnwindSafe for Once {}
133 /// State yielded to [`Once::call_once_force()`]’s closure parameter. The state
134 /// can be used to query the poison status of the [`Once`].
135 #[stable(feature = "once_poison", since = "1.51.0")]
137 pub struct OnceState {
139 set_state_on_drop_to: Cell<usize>,
142 /// Initialization value for static [`Once`] values.
147 /// use std::sync::{Once, ONCE_INIT};
149 /// static START: Once = ONCE_INIT;
151 #[stable(feature = "rust1", since = "1.0.0")]
154 reason = "the `new` function is now preferred",
155 suggestion = "Once::new()"
157 pub const ONCE_INIT: Once = Once::new();
159 // Four states that a Once can be in, encoded into the lower bits of
160 // `state_and_queue` in the Once structure.
161 const INCOMPLETE: usize = 0x0;
162 const POISONED: usize = 0x1;
163 const RUNNING: usize = 0x2;
164 const COMPLETE: usize = 0x3;
166 // Mask to learn about the state. All other bits are the queue of waiters if
167 // this is in the RUNNING state.
168 const STATE_MASK: usize = 0x3;
170 // Representation of a node in the linked list of waiters, used while in the
172 // Note: `Waiter` can't hold a mutable pointer to the next thread, because then
173 // `wait` would both hand out a mutable reference to its `Waiter` node, and keep
174 // a shared reference to check `signaled`. Instead we hold shared references and
175 // use interior mutability.
176 #[repr(align(4))] // Ensure the two lower bits are free to use as state bits.
178 thread: Cell<Option<Thread>>,
179 signaled: AtomicBool,
183 // Head of a linked list of waiters.
184 // Every node is a struct on the stack of a waiting thread.
185 // Will wake up the waiters when it gets dropped, i.e. also on panic.
186 struct WaiterQueue<'a> {
187 state_and_queue: &'a AtomicUsize,
188 set_state_on_drop_to: usize,
192 /// Creates a new `Once` value.
194 #[stable(feature = "once_new", since = "1.2.0")]
195 #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
197 pub const fn new() -> Once {
198 Once { state_and_queue: AtomicUsize::new(INCOMPLETE), _marker: marker::PhantomData }
201 /// Performs an initialization routine once and only once. The given closure
202 /// will be executed if this is the first time `call_once` has been called,
203 /// and otherwise the routine will *not* be invoked.
205 /// This method will block the calling thread if another initialization
206 /// routine is currently running.
208 /// When this function returns, it is guaranteed that some initialization
209 /// has run and completed (it might not be the closure specified). It is also
210 /// guaranteed that any memory writes performed by the executed closure can
211 /// be reliably observed by other threads at this point (there is a
212 /// happens-before relation between the closure and code executing after the
215 /// If the given closure recursively invokes `call_once` on the same [`Once`]
216 /// instance the exact behavior is not specified, allowed outcomes are
217 /// a panic or a deadlock.
222 /// use std::sync::Once;
224 /// static mut VAL: usize = 0;
225 /// static INIT: Once = Once::new();
227 /// // Accessing a `static mut` is unsafe much of the time, but if we do so
228 /// // in a synchronized fashion (e.g., write once or read all) then we're
231 /// // This function will only call `expensive_computation` once, and will
232 /// // otherwise always return the value returned from the first invocation.
233 /// fn get_cached_val() -> usize {
235 /// INIT.call_once(|| {
236 /// VAL = expensive_computation();
242 /// fn expensive_computation() -> usize {
250 /// The closure `f` will only be executed once if this is called
251 /// concurrently amongst many threads. If that closure panics, however, then
252 /// it will *poison* this [`Once`] instance, causing all future invocations of
253 /// `call_once` to also panic.
255 /// This is similar to [poisoning with mutexes][poison].
257 /// [poison]: struct.Mutex.html#poisoning
258 #[stable(feature = "rust1", since = "1.0.0")]
260 pub fn call_once<F>(&self, f: F)
265 if self.is_completed() {
270 self.call_inner(false, &mut |_| f.take().unwrap()());
273 /// Performs the same function as [`call_once()`] except ignores poisoning.
275 /// Unlike [`call_once()`], if this [`Once`] has been poisoned (i.e., a previous
276 /// call to [`call_once()`] or [`call_once_force()`] caused a panic), calling
277 /// [`call_once_force()`] will still invoke the closure `f` and will _not_
278 /// result in an immediate panic. If `f` panics, the [`Once`] will remain
279 /// in a poison state. If `f` does _not_ panic, the [`Once`] will no
280 /// longer be in a poison state and all future calls to [`call_once()`] or
281 /// [`call_once_force()`] will be no-ops.
283 /// The closure `f` is yielded a [`OnceState`] structure which can be used
284 /// to query the poison status of the [`Once`].
286 /// [`call_once()`]: Once::call_once
287 /// [`call_once_force()`]: Once::call_once_force
292 /// use std::sync::Once;
295 /// static INIT: Once = Once::new();
297 /// // poison the once
298 /// let handle = thread::spawn(|| {
299 /// INIT.call_once(|| panic!());
301 /// assert!(handle.join().is_err());
303 /// // poisoning propagates
304 /// let handle = thread::spawn(|| {
305 /// INIT.call_once(|| {});
307 /// assert!(handle.join().is_err());
309 /// // call_once_force will still run and reset the poisoned state
310 /// INIT.call_once_force(|state| {
311 /// assert!(state.is_poisoned());
314 /// // once any success happens, we stop propagating the poison
315 /// INIT.call_once(|| {});
317 #[stable(feature = "once_poison", since = "1.51.0")]
318 pub fn call_once_force<F>(&self, f: F)
320 F: FnOnce(&OnceState),
323 if self.is_completed() {
328 self.call_inner(true, &mut |p| f.take().unwrap()(p));
331 /// Returns `true` if some [`call_once()`] call has completed
332 /// successfully. Specifically, `is_completed` will return false in
333 /// the following situations:
334 /// * [`call_once()`] was not called at all,
335 /// * [`call_once()`] was called, but has not yet completed,
336 /// * the [`Once`] instance is poisoned
338 /// This function returning `false` does not mean that [`Once`] has not been
339 /// executed. For example, it may have been executed in the time between
340 /// when `is_completed` starts executing and when it returns, in which case
341 /// the `false` return value would be stale (but still permissible).
343 /// [`call_once()`]: Once::call_once
348 /// use std::sync::Once;
350 /// static INIT: Once = Once::new();
352 /// assert_eq!(INIT.is_completed(), false);
353 /// INIT.call_once(|| {
354 /// assert_eq!(INIT.is_completed(), false);
356 /// assert_eq!(INIT.is_completed(), true);
360 /// use std::sync::Once;
363 /// static INIT: Once = Once::new();
365 /// assert_eq!(INIT.is_completed(), false);
366 /// let handle = thread::spawn(|| {
367 /// INIT.call_once(|| panic!());
369 /// assert!(handle.join().is_err());
370 /// assert_eq!(INIT.is_completed(), false);
372 #[stable(feature = "once_is_completed", since = "1.43.0")]
374 pub fn is_completed(&self) -> bool {
375 // An `Acquire` load is enough because that makes all the initialization
376 // operations visible to us, and, this being a fast path, weaker
377 // ordering helps with performance. This `Acquire` synchronizes with
378 // `Release` operations on the slow path.
379 self.state_and_queue.load(Ordering::Acquire) == COMPLETE
382 // This is a non-generic function to reduce the monomorphization cost of
383 // using `call_once` (this isn't exactly a trivial or small implementation).
385 // Additionally, this is tagged with `#[cold]` as it should indeed be cold
386 // and it helps let LLVM know that calls to this function should be off the
387 // fast path. Essentially, this should help generate more straight line code
390 // Finally, this takes an `FnMut` instead of a `FnOnce` because there's
391 // currently no way to take an `FnOnce` and call it via virtual dispatch
392 // without some allocation overhead.
395 fn call_inner(&self, ignore_poisoning: bool, init: &mut dyn FnMut(&OnceState)) {
396 let mut state_and_queue = self.state_and_queue.load(Ordering::Acquire);
398 match state_and_queue {
400 POISONED if !ignore_poisoning => {
401 // Panic to propagate the poison.
402 panic!("Once instance has previously been poisoned");
404 POISONED | INCOMPLETE => {
405 // Try to register this thread as the one RUNNING.
406 let exchange_result = self.state_and_queue.compare_exchange(
412 if let Err(old) = exchange_result {
413 state_and_queue = old;
416 // `waiter_queue` will manage other waiting threads, and
417 // wake them up on drop.
418 let mut waiter_queue = WaiterQueue {
419 state_and_queue: &self.state_and_queue,
420 set_state_on_drop_to: POISONED,
422 // Run the initialization function, letting it know if we're
424 let init_state = OnceState {
425 poisoned: state_and_queue == POISONED,
426 set_state_on_drop_to: Cell::new(COMPLETE),
429 waiter_queue.set_state_on_drop_to = init_state.set_state_on_drop_to.get();
433 // All other values must be RUNNING with possibly a
434 // pointer to the waiter queue in the more significant bits.
435 assert!(state_and_queue & STATE_MASK == RUNNING);
436 wait(&self.state_and_queue, state_and_queue);
437 state_and_queue = self.state_and_queue.load(Ordering::Acquire);
444 fn wait(state_and_queue: &AtomicUsize, mut current_state: usize) {
445 // Note: the following code was carefully written to avoid creating a
446 // mutable reference to `node` that gets aliased.
448 // Don't queue this thread if the status is no longer running,
449 // otherwise we will not be woken up.
450 if current_state & STATE_MASK != RUNNING {
454 // Create the node for our current thread.
456 thread: Cell::new(Some(thread::current())),
457 signaled: AtomicBool::new(false),
458 next: (current_state & !STATE_MASK) as *const Waiter,
460 let me = &node as *const Waiter as usize;
462 // Try to slide in the node at the head of the linked list, making sure
463 // that another thread didn't just replace the head of the linked list.
464 let exchange_result = state_and_queue.compare_exchange(
470 if let Err(old) = exchange_result {
475 // We have enqueued ourselves, now lets wait.
476 // It is important not to return before being signaled, otherwise we
477 // would drop our `Waiter` node and leave a hole in the linked list
478 // (and a dangling reference). Guard against spurious wakeups by
479 // reparking ourselves until we are signaled.
480 while !node.signaled.load(Ordering::Acquire) {
481 // If the managing thread happens to signal and unpark us before we
482 // can park ourselves, the result could be this thread never gets
483 // unparked. Luckily `park` comes with the guarantee that if it got
484 // an `unpark` just before on an unparked thread it does not park.
491 #[stable(feature = "std_debug", since = "1.16.0")]
492 impl fmt::Debug for Once {
493 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
494 f.debug_struct("Once").finish_non_exhaustive()
498 impl Drop for WaiterQueue<'_> {
500 // Swap out our state with however we finished.
501 let state_and_queue =
502 self.state_and_queue.swap(self.set_state_on_drop_to, Ordering::AcqRel);
504 // We should only ever see an old state which was RUNNING.
505 assert_eq!(state_and_queue & STATE_MASK, RUNNING);
507 // Walk the entire linked list of waiters and wake them up (in lifo
508 // order, last to register is first to wake up).
510 // Right after setting `node.signaled = true` the other thread may
511 // free `node` if there happens to be has a spurious wakeup.
512 // So we have to take out the `thread` field and copy the pointer to
514 let mut queue = (state_and_queue & !STATE_MASK) as *const Waiter;
515 while !queue.is_null() {
516 let next = (*queue).next;
517 let thread = (*queue).thread.take().unwrap();
518 (*queue).signaled.store(true, Ordering::Release);
519 // ^- FIXME (maybe): This is another case of issue #55005
520 // `store()` has a potentially dangling ref to `signaled`.
529 /// Returns `true` if the associated [`Once`] was poisoned prior to the
530 /// invocation of the closure passed to [`Once::call_once_force()`].
534 /// A poisoned [`Once`]:
537 /// use std::sync::Once;
540 /// static INIT: Once = Once::new();
542 /// // poison the once
543 /// let handle = thread::spawn(|| {
544 /// INIT.call_once(|| panic!());
546 /// assert!(handle.join().is_err());
548 /// INIT.call_once_force(|state| {
549 /// assert!(state.is_poisoned());
553 /// An unpoisoned [`Once`]:
556 /// use std::sync::Once;
558 /// static INIT: Once = Once::new();
560 /// INIT.call_once_force(|state| {
561 /// assert!(!state.is_poisoned());
563 #[stable(feature = "once_poison", since = "1.51.0")]
564 pub fn is_poisoned(&self) -> bool {
568 /// Poison the associated [`Once`] without explicitly panicking.
569 // NOTE: This is currently only exposed for the `lazy` module
570 pub(crate) fn poison(&self) {
571 self.set_state_on_drop_to.set(POISONED);