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
58 use sync::atomic::{AtomicUsize, AtomicBool, Ordering};
59 use thread::{self, Thread};
61 /// A synchronization primitive which can be used to run a one-time global
62 /// initialization. Useful for one-time initialization for FFI or related
63 /// functionality. This type can only be constructed with the [`ONCE_INIT`]
64 /// value or the equivalent [`Once::new`] constructor.
66 /// [`ONCE_INIT`]: constant.ONCE_INIT.html
67 /// [`Once::new`]: struct.Once.html#method.new
72 /// use std::sync::Once;
74 /// static START: Once = Once::new();
76 /// START.call_once(|| {
77 /// // run initialization here
80 #[stable(feature = "rust1", since = "1.0.0")]
82 // This `state` word is actually an encoded version of just a pointer to a
83 // `Waiter`, so we add the `PhantomData` appropriately.
85 _marker: marker::PhantomData<*mut Waiter>,
88 // The `PhantomData` of a raw pointer removes these two auto traits, but we
89 // enforce both below in the implementation so this should be safe to add.
90 #[stable(feature = "rust1", since = "1.0.0")]
91 unsafe impl Sync for Once {}
92 #[stable(feature = "rust1", since = "1.0.0")]
93 unsafe impl Send for Once {}
95 /// State yielded to [`call_once_force`]’s closure parameter. The state can be
96 /// used to query the poison status of the [`Once`].
98 /// [`call_once_force`]: struct.Once.html#method.call_once_force
99 /// [`Once`]: struct.Once.html
100 #[unstable(feature = "once_poison", issue = "33577")]
102 pub struct OnceState {
106 /// Initialization value for static [`Once`] values.
108 /// [`Once`]: struct.Once.html
113 /// use std::sync::{Once, ONCE_INIT};
115 /// static START: Once = ONCE_INIT;
117 #[stable(feature = "rust1", since = "1.0.0")]
118 pub const ONCE_INIT: Once = Once::new();
120 // Four states that a Once can be in, encoded into the lower bits of `state` in
121 // the Once structure.
122 const INCOMPLETE: usize = 0x0;
123 const POISONED: usize = 0x1;
124 const RUNNING: usize = 0x2;
125 const COMPLETE: usize = 0x3;
127 // Mask to learn about the state. All other bits are the queue of waiters if
128 // this is in the RUNNING state.
129 const STATE_MASK: usize = 0x3;
131 // Representation of a node in the linked list of waiters in the RUNNING state.
133 thread: Option<Thread>,
134 signaled: AtomicBool,
138 // Helper struct used to clean up after a closure call with a `Drop`
139 // implementation to also run on panic.
146 /// Creates a new `Once` value.
147 #[stable(feature = "once_new", since = "1.2.0")]
148 pub const fn new() -> Once {
150 state: AtomicUsize::new(INCOMPLETE),
151 _marker: marker::PhantomData,
155 /// Performs an initialization routine once and only once. The given closure
156 /// will be executed if this is the first time `call_once` has been called,
157 /// and otherwise the routine will *not* be invoked.
159 /// This method will block the calling thread if another initialization
160 /// routine is currently running.
162 /// When this function returns, it is guaranteed that some initialization
163 /// has run and completed (it may not be the closure specified). It is also
164 /// guaranteed that any memory writes performed by the executed closure can
165 /// be reliably observed by other threads at this point (there is a
166 /// happens-before relation between the closure and code executing after the
169 /// If the given closure recursively invokes `call_once` on the same `Once`
170 /// instance the exact behavior is not specified, allowed outcomes are
171 /// a panic or a deadlock.
176 /// use std::sync::Once;
178 /// static mut VAL: usize = 0;
179 /// static INIT: Once = Once::new();
181 /// // Accessing a `static mut` is unsafe much of the time, but if we do so
182 /// // in a synchronized fashion (e.g., write once or read all) then we're
185 /// // This function will only call `expensive_computation` once, and will
186 /// // otherwise always return the value returned from the first invocation.
187 /// fn get_cached_val() -> usize {
189 /// INIT.call_once(|| {
190 /// VAL = expensive_computation();
196 /// fn expensive_computation() -> usize {
204 /// The closure `f` will only be executed once if this is called
205 /// concurrently amongst many threads. If that closure panics, however, then
206 /// it will *poison* this `Once` instance, causing all future invocations of
207 /// `call_once` to also panic.
209 /// This is similar to [poisoning with mutexes][poison].
211 /// [poison]: struct.Mutex.html#poisoning
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn call_once<F>(&self, f: F) where F: FnOnce() {
215 if self.is_completed() {
220 self.call_inner(false, &mut |_| f.take().unwrap()());
223 /// Performs the same function as [`call_once`] except ignores poisoning.
225 /// Unlike [`call_once`], if this `Once` has been poisoned (i.e., a previous
226 /// call to `call_once` or `call_once_force` caused a panic), calling
227 /// `call_once_force` will still invoke the closure `f` and will _not_
228 /// result in an immediate panic. If `f` panics, the `Once` will remain
229 /// in a poison state. If `f` does _not_ panic, the `Once` will no
230 /// longer be in a poison state and all future calls to `call_once` or
231 /// `call_one_force` will be no-ops.
233 /// The closure `f` is yielded a [`OnceState`] structure which can be used
234 /// to query the poison status of the `Once`.
236 /// [`call_once`]: struct.Once.html#method.call_once
237 /// [`OnceState`]: struct.OnceState.html
242 /// #![feature(once_poison)]
244 /// use std::sync::Once;
247 /// static INIT: Once = Once::new();
249 /// // poison the once
250 /// let handle = thread::spawn(|| {
251 /// INIT.call_once(|| panic!());
253 /// assert!(handle.join().is_err());
255 /// // poisoning propagates
256 /// let handle = thread::spawn(|| {
257 /// INIT.call_once(|| {});
259 /// assert!(handle.join().is_err());
261 /// // call_once_force will still run and reset the poisoned state
262 /// INIT.call_once_force(|state| {
263 /// assert!(state.poisoned());
266 /// // once any success happens, we stop propagating the poison
267 /// INIT.call_once(|| {});
269 #[unstable(feature = "once_poison", issue = "33577")]
270 pub fn call_once_force<F>(&self, f: F) where F: FnOnce(&OnceState) {
272 if self.is_completed() {
277 self.call_inner(true, &mut |p| {
278 f.take().unwrap()(&OnceState { poisoned: p })
282 /// Returns `true` if some `call_once` call has completed
283 /// successfully. Specifically, `is_completed` will return false in
284 /// the following situations:
285 /// * `call_once` was not called at all,
286 /// * `call_once` was called, but has not yet completed,
287 /// * the `Once` instance is poisoned
289 /// It is also possible that immediately after `is_completed`
290 /// returns false, some other thread finishes executing
296 /// #![feature(once_is_completed)]
297 /// use std::sync::Once;
299 /// static INIT: Once = Once::new();
301 /// assert_eq!(INIT.is_completed(), false);
302 /// INIT.call_once(|| {
303 /// assert_eq!(INIT.is_completed(), false);
305 /// assert_eq!(INIT.is_completed(), true);
309 /// #![feature(once_is_completed)]
310 /// use std::sync::Once;
313 /// static INIT: Once = Once::new();
315 /// assert_eq!(INIT.is_completed(), false);
316 /// let handle = thread::spawn(|| {
317 /// INIT.call_once(|| panic!());
319 /// assert!(handle.join().is_err());
320 /// assert_eq!(INIT.is_completed(), false);
322 #[unstable(feature = "once_is_completed", issue = "54890")]
324 pub fn is_completed(&self) -> bool {
325 // An `Acquire` load is enough because that makes all the initialization
326 // operations visible to us, and, this being a fast path, weaker
327 // ordering helps with performance. This `Acquire` synchronizes with
328 // `SeqCst` operations on the slow path.
329 self.state.load(Ordering::Acquire) == COMPLETE
332 // This is a non-generic function to reduce the monomorphization cost of
333 // using `call_once` (this isn't exactly a trivial or small implementation).
335 // Additionally, this is tagged with `#[cold]` as it should indeed be cold
336 // and it helps let LLVM know that calls to this function should be off the
337 // fast path. Essentially, this should help generate more straight line code
340 // Finally, this takes an `FnMut` instead of a `FnOnce` because there's
341 // currently no way to take an `FnOnce` and call it via virtual dispatch
342 // without some allocation overhead.
345 ignore_poisoning: bool,
346 init: &mut dyn FnMut(bool)) {
348 // This cold path uses SeqCst consistently because the
349 // performance difference really does not matter there, and
350 // SeqCst minimizes the chances of something going wrong.
351 let mut state = self.state.load(Ordering::SeqCst);
355 // If we're complete, then there's nothing to do, we just
356 // jettison out as we shouldn't run the closure.
359 // If we're poisoned and we're not in a mode to ignore
360 // poisoning, then we panic here to propagate the poison.
361 POISONED if !ignore_poisoning => {
362 panic!("Once instance has previously been poisoned");
365 // Otherwise if we see a poisoned or otherwise incomplete state
366 // we will attempt to move ourselves into the RUNNING state. If
367 // we succeed, then the queue of waiters starts at null (all 0
371 let old = self.state.compare_and_swap(state, RUNNING,
378 // Run the initialization routine, letting it know if we're
379 // poisoned or not. The `Finish` struct is then dropped, and
380 // the `Drop` implementation here is responsible for waking
381 // up other waiters both in the normal return and panicking
383 let mut complete = Finish {
387 init(state == POISONED);
388 complete.panicked = false;
392 // All other values we find should correspond to the RUNNING
393 // state with an encoded waiter list in the more significant
394 // bits. We attempt to enqueue ourselves by moving us to the
395 // head of the list and bail out if we ever see a state that's
398 assert!(state & STATE_MASK == RUNNING);
399 let mut node = Waiter {
400 thread: Some(thread::current()),
401 signaled: AtomicBool::new(false),
402 next: ptr::null_mut(),
404 let me = &mut node as *mut Waiter as usize;
405 assert!(me & STATE_MASK == 0);
407 while state & STATE_MASK == RUNNING {
408 node.next = (state & !STATE_MASK) as *mut Waiter;
409 let old = self.state.compare_and_swap(state,
417 // Once we've enqueued ourselves, wait in a loop.
418 // Afterwards reload the state and continue with what we
419 // were doing from before.
420 while !node.signaled.load(Ordering::SeqCst) {
423 state = self.state.load(Ordering::SeqCst);
432 #[stable(feature = "std_debug", since = "1.16.0")]
433 impl fmt::Debug for Once {
434 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
439 impl Drop for Finish<'_> {
441 // Swap out our state with however we finished. We should only ever see
442 // an old state which was RUNNING.
443 let queue = if self.panicked {
444 self.me.state.swap(POISONED, Ordering::SeqCst)
446 self.me.state.swap(COMPLETE, Ordering::SeqCst)
448 assert_eq!(queue & STATE_MASK, RUNNING);
450 // Decode the RUNNING to a list of waiters, then walk that entire list
451 // and wake them up. Note that it is crucial that after we store `true`
452 // in the node it can be free'd! As a result we load the `thread` to
453 // signal ahead of time and then unpark it after the store.
455 let mut queue = (queue & !STATE_MASK) as *mut Waiter;
456 while !queue.is_null() {
457 let next = (*queue).next;
458 let thread = (*queue).thread.take().unwrap();
459 (*queue).signaled.store(true, Ordering::SeqCst);
468 /// Returns `true` if the associated [`Once`] was poisoned prior to the
469 /// invocation of the closure passed to [`call_once_force`].
471 /// [`call_once_force`]: struct.Once.html#method.call_once_force
472 /// [`Once`]: struct.Once.html
476 /// A poisoned `Once`:
479 /// #![feature(once_poison)]
481 /// use std::sync::Once;
484 /// static INIT: Once = Once::new();
486 /// // poison the once
487 /// let handle = thread::spawn(|| {
488 /// INIT.call_once(|| panic!());
490 /// assert!(handle.join().is_err());
492 /// INIT.call_once_force(|state| {
493 /// assert!(state.poisoned());
497 /// An unpoisoned `Once`:
500 /// #![feature(once_poison)]
502 /// use std::sync::Once;
504 /// static INIT: Once = Once::new();
506 /// INIT.call_once_force(|state| {
507 /// assert!(!state.poisoned());
509 #[unstable(feature = "once_poison", issue = "33577")]
510 pub fn poisoned(&self) -> bool {
515 #[cfg(all(test, not(target_os = "emscripten")))]
518 use sync::mpsc::channel;
524 static O: Once = Once::new();
526 O.call_once(|| a += 1);
528 O.call_once(|| a += 1);
534 static O: Once = Once::new();
535 static mut RUN: bool = false;
537 let (tx, rx) = channel();
540 thread::spawn(move|| {
541 for _ in 0..4 { thread::yield_now() }
549 tx.send(()).unwrap();
568 static O: Once = Once::new();
571 let t = panic::catch_unwind(|| {
572 O.call_once(|| panic!());
576 // poisoning propagates
577 let t = panic::catch_unwind(|| {
582 // we can subvert poisoning, however
583 let mut called = false;
584 O.call_once_force(|p| {
586 assert!(p.poisoned())
590 // once any success happens, we stop propagating the poison
595 fn wait_for_force_to_finish() {
596 static O: Once = Once::new();
599 let t = panic::catch_unwind(|| {
600 O.call_once(|| panic!());
604 // make sure someone's waiting inside the once via a force
605 let (tx1, rx1) = channel();
606 let (tx2, rx2) = channel();
607 let t1 = thread::spawn(move || {
608 O.call_once_force(|p| {
609 assert!(p.poisoned());
610 tx1.send(()).unwrap();
617 // put another waiter on the once
618 let t2 = thread::spawn(|| {
619 let mut called = false;
626 tx2.send(()).unwrap();
628 assert!(t1.join().is_ok());
629 assert!(t2.join().is_ok());