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_and_swap` 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 Aquire ordering such a reordering is not
85 // allowed, so no need for SeqCst.
87 use crate::cell::Cell;
90 use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
91 use crate::thread::{self, Thread};
93 /// A synchronization primitive which can be used to run a one-time global
94 /// initialization. Useful for one-time initialization for FFI or related
95 /// functionality. This type can only be constructed with the [`Once::new`]
98 /// [`Once::new`]: struct.Once.html#method.new
103 /// use std::sync::Once;
105 /// static START: Once = Once::new();
107 /// START.call_once(|| {
108 /// // run initialization here
111 #[stable(feature = "rust1", since = "1.0.0")]
113 // `state_and_queue` is actually an a pointer to a `Waiter` with extra state
114 // bits, so we add the `PhantomData` appropriately.
115 state_and_queue: AtomicUsize,
116 _marker: marker::PhantomData<*const Waiter>,
119 // The `PhantomData` of a raw pointer removes these two auto traits, but we
120 // enforce both below in the implementation so this should be safe to add.
121 #[stable(feature = "rust1", since = "1.0.0")]
122 unsafe impl Sync for Once {}
123 #[stable(feature = "rust1", since = "1.0.0")]
124 unsafe impl Send for Once {}
126 /// State yielded to [`call_once_force`]’s closure parameter. The state can be
127 /// used to query the poison status of the [`Once`].
129 /// [`call_once_force`]: struct.Once.html#method.call_once_force
130 /// [`Once`]: struct.Once.html
131 #[unstable(feature = "once_poison", issue = "33577")]
133 pub struct OnceState {
137 /// Initialization value for static [`Once`] values.
139 /// [`Once`]: struct.Once.html
144 /// use std::sync::{Once, ONCE_INIT};
146 /// static START: Once = ONCE_INIT;
148 #[stable(feature = "rust1", since = "1.0.0")]
151 reason = "the `new` function is now preferred",
152 suggestion = "Once::new()"
154 pub const ONCE_INIT: Once = Once::new();
156 // Four states that a Once can be in, encoded into the lower bits of
157 // `state_and_queue` in the Once structure.
158 const INCOMPLETE: usize = 0x0;
159 const POISONED: usize = 0x1;
160 const RUNNING: usize = 0x2;
161 const COMPLETE: usize = 0x3;
163 // Mask to learn about the state. All other bits are the queue of waiters if
164 // this is in the RUNNING state.
165 const STATE_MASK: usize = 0x3;
167 // Representation of a node in the linked list of waiters, used while in the
169 // Note: `Waiter` can't hold a mutable pointer to the next thread, because then
170 // `wait` would both hand out a mutable reference to its `Waiter` node, and keep
171 // a shared reference to check `signaled`. Instead we hold shared references and
172 // use interior mutability.
173 #[repr(align(4))] // Ensure the two lower bits are free to use as state bits.
175 thread: Cell<Option<Thread>>,
176 signaled: AtomicBool,
180 // Head of a linked list of waiters.
181 // Every node is a struct on the stack of a waiting thread.
182 // Will wake up the waiters when it gets dropped, i.e. also on panic.
183 struct WaiterQueue<'a> {
184 state_and_queue: &'a AtomicUsize,
185 set_state_on_drop_to: usize,
189 /// Creates a new `Once` value.
190 #[stable(feature = "once_new", since = "1.2.0")]
191 #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
192 pub const fn new() -> Once {
193 Once { state_and_queue: AtomicUsize::new(INCOMPLETE), _marker: marker::PhantomData }
196 /// Performs an initialization routine once and only once. The given closure
197 /// will be executed if this is the first time `call_once` has been called,
198 /// and otherwise the routine will *not* be invoked.
200 /// This method will block the calling thread if another initialization
201 /// routine is currently running.
203 /// When this function returns, it is guaranteed that some initialization
204 /// has run and completed (it may not be the closure specified). It is also
205 /// guaranteed that any memory writes performed by the executed closure can
206 /// be reliably observed by other threads at this point (there is a
207 /// happens-before relation between the closure and code executing after the
210 /// If the given closure recursively invokes `call_once` on the same `Once`
211 /// instance the exact behavior is not specified, allowed outcomes are
212 /// a panic or a deadlock.
217 /// use std::sync::Once;
219 /// static mut VAL: usize = 0;
220 /// static INIT: Once = Once::new();
222 /// // Accessing a `static mut` is unsafe much of the time, but if we do so
223 /// // in a synchronized fashion (e.g., write once or read all) then we're
226 /// // This function will only call `expensive_computation` once, and will
227 /// // otherwise always return the value returned from the first invocation.
228 /// fn get_cached_val() -> usize {
230 /// INIT.call_once(|| {
231 /// VAL = expensive_computation();
237 /// fn expensive_computation() -> usize {
245 /// The closure `f` will only be executed once if this is called
246 /// concurrently amongst many threads. If that closure panics, however, then
247 /// it will *poison* this `Once` instance, causing all future invocations of
248 /// `call_once` to also panic.
250 /// This is similar to [poisoning with mutexes][poison].
252 /// [poison]: struct.Mutex.html#poisoning
253 #[stable(feature = "rust1", since = "1.0.0")]
254 pub fn call_once<F>(&self, f: F)
259 if self.is_completed() {
264 self.call_inner(false, &mut |_| f.take().unwrap()());
267 /// Performs the same function as [`call_once`] except ignores poisoning.
269 /// Unlike [`call_once`], if this `Once` has been poisoned (i.e., a previous
270 /// call to `call_once` or `call_once_force` caused a panic), calling
271 /// `call_once_force` will still invoke the closure `f` and will _not_
272 /// result in an immediate panic. If `f` panics, the `Once` will remain
273 /// in a poison state. If `f` does _not_ panic, the `Once` will no
274 /// longer be in a poison state and all future calls to `call_once` or
275 /// `call_one_force` will be no-ops.
277 /// The closure `f` is yielded a [`OnceState`] structure which can be used
278 /// to query the poison status of the `Once`.
280 /// [`call_once`]: struct.Once.html#method.call_once
281 /// [`OnceState`]: struct.OnceState.html
286 /// #![feature(once_poison)]
288 /// use std::sync::Once;
291 /// static INIT: Once = Once::new();
293 /// // poison the once
294 /// let handle = thread::spawn(|| {
295 /// INIT.call_once(|| panic!());
297 /// assert!(handle.join().is_err());
299 /// // poisoning propagates
300 /// let handle = thread::spawn(|| {
301 /// INIT.call_once(|| {});
303 /// assert!(handle.join().is_err());
305 /// // call_once_force will still run and reset the poisoned state
306 /// INIT.call_once_force(|state| {
307 /// assert!(state.poisoned());
310 /// // once any success happens, we stop propagating the poison
311 /// INIT.call_once(|| {});
313 #[unstable(feature = "once_poison", issue = "33577")]
314 pub fn call_once_force<F>(&self, f: F)
316 F: FnOnce(&OnceState),
319 if self.is_completed() {
324 self.call_inner(true, &mut |p| f.take().unwrap()(&OnceState { poisoned: p }));
327 /// Returns `true` if some `call_once` call has completed
328 /// successfully. Specifically, `is_completed` will return false in
329 /// the following situations:
330 /// * `call_once` was not called at all,
331 /// * `call_once` was called, but has not yet completed,
332 /// * the `Once` instance is poisoned
334 /// It is also possible that immediately after `is_completed`
335 /// returns false, some other thread finishes executing
341 /// #![feature(once_is_completed)]
342 /// use std::sync::Once;
344 /// static INIT: Once = Once::new();
346 /// assert_eq!(INIT.is_completed(), false);
347 /// INIT.call_once(|| {
348 /// assert_eq!(INIT.is_completed(), false);
350 /// assert_eq!(INIT.is_completed(), true);
354 /// #![feature(once_is_completed)]
355 /// use std::sync::Once;
358 /// static INIT: Once = Once::new();
360 /// assert_eq!(INIT.is_completed(), false);
361 /// let handle = thread::spawn(|| {
362 /// INIT.call_once(|| panic!());
364 /// assert!(handle.join().is_err());
365 /// assert_eq!(INIT.is_completed(), false);
367 #[unstable(feature = "once_is_completed", issue = "54890")]
369 pub fn is_completed(&self) -> bool {
370 // An `Acquire` load is enough because that makes all the initialization
371 // operations visible to us, and, this being a fast path, weaker
372 // ordering helps with performance. This `Acquire` synchronizes with
373 // `Release` operations on the slow path.
374 self.state_and_queue.load(Ordering::Acquire) == COMPLETE
377 // This is a non-generic function to reduce the monomorphization cost of
378 // using `call_once` (this isn't exactly a trivial or small implementation).
380 // Additionally, this is tagged with `#[cold]` as it should indeed be cold
381 // and it helps let LLVM know that calls to this function should be off the
382 // fast path. Essentially, this should help generate more straight line code
385 // Finally, this takes an `FnMut` instead of a `FnOnce` because there's
386 // currently no way to take an `FnOnce` and call it via virtual dispatch
387 // without some allocation overhead.
389 fn call_inner(&self, ignore_poisoning: bool, init: &mut dyn FnMut(bool)) {
390 let mut state_and_queue = self.state_and_queue.load(Ordering::Acquire);
392 match state_and_queue {
394 POISONED if !ignore_poisoning => {
395 // Panic to propagate the poison.
396 panic!("Once instance has previously been poisoned");
398 POISONED | INCOMPLETE => {
399 // Try to register this thread as the one RUNNING.
400 let old = self.state_and_queue.compare_and_swap(
405 if old != state_and_queue {
406 state_and_queue = old;
409 // `waiter_queue` will manage other waiting threads, and
410 // wake them up on drop.
411 let mut waiter_queue = WaiterQueue {
412 state_and_queue: &self.state_and_queue,
413 set_state_on_drop_to: POISONED,
415 // Run the initialization function, letting it know if we're
417 init(state_and_queue == POISONED);
418 waiter_queue.set_state_on_drop_to = COMPLETE;
422 // All other values must be RUNNING with possibly a
423 // pointer to the waiter queue in the more significant bits.
424 assert!(state_and_queue & STATE_MASK == RUNNING);
425 wait(&self.state_and_queue, state_and_queue);
426 state_and_queue = self.state_and_queue.load(Ordering::Acquire);
433 fn wait(state_and_queue: &AtomicUsize, mut current_state: usize) {
434 // Note: the following code was carefully written to avoid creating a
435 // mutable reference to `node` that gets aliased.
437 // Don't queue this thread if the status is no longer running,
438 // otherwise we will not be woken up.
439 if current_state & STATE_MASK != RUNNING {
443 // Create the node for our current thread.
445 thread: Cell::new(Some(thread::current())),
446 signaled: AtomicBool::new(false),
447 next: (current_state & !STATE_MASK) as *const Waiter,
449 let me = &node as *const Waiter as usize;
451 // Try to slide in the node at the head of the linked list, making sure
452 // that another thread didn't just replace the head of the linked list.
453 let old = state_and_queue.compare_and_swap(current_state, me | RUNNING, Ordering::Release);
454 if old != current_state {
459 // We have enqueued ourselves, now lets wait.
460 // It is important not to return before being signaled, otherwise we
461 // would drop our `Waiter` node and leave a hole in the linked list
462 // (and a dangling reference). Guard against spurious wakeups by
463 // reparking ourselves until we are signaled.
464 while !node.signaled.load(Ordering::Acquire) {
465 // If the managing thread happens to signal and unpark us before we
466 // can park ourselves, the result could be this thread never gets
467 // unparked. Luckily `park` comes with the guarantee that if it got
468 // an `unpark` just before on an unparked thread is does not park.
475 #[stable(feature = "std_debug", since = "1.16.0")]
476 impl fmt::Debug for Once {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 impl Drop for WaiterQueue<'_> {
484 // Swap out our state with however we finished.
485 let state_and_queue =
486 self.state_and_queue.swap(self.set_state_on_drop_to, Ordering::AcqRel);
488 // We should only ever see an old state which was RUNNING.
489 assert_eq!(state_and_queue & STATE_MASK, RUNNING);
491 // Walk the entire linked list of waiters and wake them up (in lifo
492 // order, last to register is first to wake up).
494 // Right after setting `node.signaled = true` the other thread may
495 // free `node` if there happens to be has a spurious wakeup.
496 // So we have to take out the `thread` field and copy the pointer to
498 let mut queue = (state_and_queue & !STATE_MASK) as *const Waiter;
499 while !queue.is_null() {
500 let next = (*queue).next;
501 let thread = (*queue).thread.replace(None).unwrap();
502 (*queue).signaled.store(true, Ordering::Release);
503 // ^- FIXME (maybe): This is another case of issue #55005
504 // `store()` has a potentially dangling ref to `signaled`.
513 /// Returns `true` if the associated [`Once`] was poisoned prior to the
514 /// invocation of the closure passed to [`call_once_force`].
516 /// [`call_once_force`]: struct.Once.html#method.call_once_force
517 /// [`Once`]: struct.Once.html
521 /// A poisoned `Once`:
524 /// #![feature(once_poison)]
526 /// use std::sync::Once;
529 /// static INIT: Once = Once::new();
531 /// // poison the once
532 /// let handle = thread::spawn(|| {
533 /// INIT.call_once(|| panic!());
535 /// assert!(handle.join().is_err());
537 /// INIT.call_once_force(|state| {
538 /// assert!(state.poisoned());
542 /// An unpoisoned `Once`:
545 /// #![feature(once_poison)]
547 /// use std::sync::Once;
549 /// static INIT: Once = Once::new();
551 /// INIT.call_once_force(|state| {
552 /// assert!(!state.poisoned());
554 #[unstable(feature = "once_poison", issue = "33577")]
555 pub fn poisoned(&self) -> bool {
560 #[cfg(all(test, not(target_os = "emscripten")))]
564 use crate::sync::mpsc::channel;
569 static O: Once = Once::new();
571 O.call_once(|| a += 1);
573 O.call_once(|| a += 1);
579 static O: Once = Once::new();
580 static mut RUN: bool = false;
582 let (tx, rx) = channel();
585 thread::spawn(move || {
596 tx.send(()).unwrap();
615 static O: Once = Once::new();
618 let t = panic::catch_unwind(|| {
619 O.call_once(|| panic!());
623 // poisoning propagates
624 let t = panic::catch_unwind(|| {
629 // we can subvert poisoning, however
630 let mut called = false;
631 O.call_once_force(|p| {
633 assert!(p.poisoned())
637 // once any success happens, we stop propagating the poison
642 fn wait_for_force_to_finish() {
643 static O: Once = Once::new();
646 let t = panic::catch_unwind(|| {
647 O.call_once(|| panic!());
651 // make sure someone's waiting inside the once via a force
652 let (tx1, rx1) = channel();
653 let (tx2, rx2) = channel();
654 let t1 = thread::spawn(move || {
655 O.call_once_force(|p| {
656 assert!(p.poisoned());
657 tx1.send(()).unwrap();
664 // put another waiter on the once
665 let t2 = thread::spawn(|| {
666 let mut called = false;
673 tx2.send(()).unwrap();
675 assert!(t1.join().is_ok());
676 assert!(t2.join().is_ok());