Skip to main content

std/sync/
once.rs

1//! A "once initialization" primitive
2//!
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.
5
6use crate::fmt;
7use crate::panic::{RefUnwindSafe, UnwindSafe};
8use crate::sys::sync as sys;
9
10/// A low-level synchronization primitive for one-time global execution.
11///
12/// Previously this was the only "execute once" synchronization in `std`.
13/// Other libraries implemented novel synchronizing types with `Once`, like
14/// [`OnceLock<T>`] or [`LazyLock<T, F>`], before those were added to `std`.
15/// `OnceLock<T>` in particular supersedes `Once` in functionality and should
16/// be preferred for the common case where the `Once` is associated with data.
17///
18/// This type can only be constructed with [`Once::new()`].
19///
20/// # Examples
21///
22/// ```
23/// use std::sync::Once;
24///
25/// static START: Once = Once::new();
26///
27/// START.call_once(|| {
28///     // run initialization here
29/// });
30/// ```
31///
32/// [`OnceLock<T>`]: crate::sync::OnceLock
33/// [`LazyLock<T, F>`]: crate::sync::LazyLock
34#[stable(feature = "rust1", since = "1.0.0")]
35pub struct Once {
36    inner: sys::Once,
37}
38
39#[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
40impl UnwindSafe for Once {}
41
42#[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
43impl RefUnwindSafe for Once {}
44
45/// State yielded to [`Once::call_once_force()`]’s closure parameter. The state
46/// can be used to query the poison status of the [`Once`].
47#[stable(feature = "once_poison", since = "1.51.0")]
48pub struct OnceState {
49    pub(crate) inner: sys::OnceState,
50}
51
52/// Used for the internal implementation of `sys::sync::once` on different platforms and the
53/// [`LazyLock`](crate::sync::LazyLock) implementation.
54pub(crate) enum OnceExclusiveState {
55    Incomplete,
56    Poisoned,
57    Complete,
58}
59
60/// Initialization value for static [`Once`] values.
61///
62/// # Examples
63///
64/// ```
65/// use std::sync::{Once, ONCE_INIT};
66///
67/// static START: Once = ONCE_INIT;
68/// ```
69#[stable(feature = "rust1", since = "1.0.0")]
70#[deprecated(
71    since = "1.38.0",
72    note = "the `Once::new()` function is now preferred",
73    suggestion = "Once::new()"
74)]
75#[expect(clippy::declare_interior_mutable_const, reason = "legacy Once initializer")]
76pub const ONCE_INIT: Once = Once::new();
77
78impl Once {
79    /// Creates a new `Once` value.
80    #[inline]
81    #[stable(feature = "once_new", since = "1.2.0")]
82    #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
83    #[must_use]
84    pub const fn new() -> Once {
85        Once { inner: sys::Once::new() }
86    }
87
88    /// Creates a new `Once` value that starts already completed.
89    #[inline]
90    #[must_use]
91    pub(crate) const fn new_complete() -> Once {
92        Once { inner: sys::Once::new_complete() }
93    }
94
95    /// Performs an initialization routine once and only once. The given closure
96    /// will be executed if this is the first time `call_once` has been called,
97    /// and otherwise the routine will *not* be invoked.
98    ///
99    /// This method will block the calling thread if another initialization
100    /// routine is currently running.
101    ///
102    /// When this function returns, it is guaranteed that some initialization
103    /// has run and completed (it might not be the closure specified). It is also
104    /// guaranteed that any memory writes performed by the executed closure can
105    /// be reliably observed by other threads at this point (there is a
106    /// happens-before relation between the closure and code executing after the
107    /// return).
108    ///
109    /// If the given closure recursively invokes `call_once` on the same [`Once`]
110    /// instance, the exact behavior is not specified: allowed outcomes are
111    /// a panic or a deadlock.
112    ///
113    /// # Examples
114    ///
115    /// ```
116    /// use std::sync::Once;
117    ///
118    /// static mut VAL: usize = 0;
119    /// static INIT: Once = Once::new();
120    ///
121    /// // Accessing a `static mut` is unsafe much of the time, but if we do so
122    /// // in a synchronized fashion (e.g., write once or read all) then we're
123    /// // good to go!
124    /// //
125    /// // This function will only call `expensive_computation` once, and will
126    /// // otherwise always return the value returned from the first invocation.
127    /// fn get_cached_val() -> usize {
128    ///     unsafe {
129    ///         INIT.call_once(|| {
130    ///             VAL = expensive_computation();
131    ///         });
132    ///         VAL
133    ///     }
134    /// }
135    ///
136    /// fn expensive_computation() -> usize {
137    ///     // ...
138    /// # 2
139    /// }
140    /// ```
141    ///
142    /// # Panics
143    ///
144    /// The closure `f` will only be executed once even if this is called
145    /// concurrently amongst many threads. If that closure panics, however, then
146    /// it will *poison* this [`Once`] instance, causing all future invocations of
147    /// `call_once` to also panic.
148    ///
149    /// This is similar to [poisoning with mutexes][poison], but this mechanism
150    /// is guaranteed to never skip panics within `f`.
151    ///
152    /// [poison]: struct.Mutex.html#poisoning
153    #[inline]
154    #[stable(feature = "rust1", since = "1.0.0")]
155    #[track_caller]
156    #[rustc_should_not_be_called_on_const_items]
157    pub fn call_once<F>(&self, f: F)
158    where
159        F: FnOnce(),
160    {
161        // Fast path check
162        if self.inner.is_completed() {
163            return;
164        }
165
166        let mut f = Some(f);
167        self.inner.call(false, &mut |_| f.take().unwrap()());
168    }
169
170    /// Performs the same function as [`call_once()`] except ignores poisoning.
171    ///
172    /// Unlike [`call_once()`], if this [`Once`] has been poisoned (i.e., a previous
173    /// call to [`call_once()`] or [`call_once_force()`] caused a panic), calling
174    /// [`call_once_force()`] will still invoke the closure `f` and will _not_
175    /// result in an immediate panic. If `f` panics, the [`Once`] will remain
176    /// in a poison state. If `f` does _not_ panic, the [`Once`] will no
177    /// longer be in a poison state and all future calls to [`call_once()`] or
178    /// [`call_once_force()`] will be no-ops.
179    ///
180    /// The closure `f` is yielded a [`OnceState`] structure which can be used
181    /// to query the poison status of the [`Once`].
182    ///
183    /// [`call_once()`]: Once::call_once
184    /// [`call_once_force()`]: Once::call_once_force
185    ///
186    /// # Examples
187    ///
188    /// ```
189    /// use std::sync::Once;
190    /// use std::thread;
191    ///
192    /// static INIT: Once = Once::new();
193    ///
194    /// // poison the once
195    /// let handle = thread::spawn(|| {
196    ///     INIT.call_once(|| panic!());
197    /// });
198    /// assert!(handle.join().is_err());
199    ///
200    /// // poisoning propagates
201    /// let handle = thread::spawn(|| {
202    ///     INIT.call_once(|| {});
203    /// });
204    /// assert!(handle.join().is_err());
205    ///
206    /// // call_once_force will still run and reset the poisoned state
207    /// INIT.call_once_force(|state| {
208    ///     assert!(state.is_poisoned());
209    /// });
210    ///
211    /// // once any success happens, we stop propagating the poison
212    /// INIT.call_once(|| {});
213    /// ```
214    #[inline]
215    #[stable(feature = "once_poison", since = "1.51.0")]
216    #[rustc_should_not_be_called_on_const_items]
217    pub fn call_once_force<F>(&self, f: F)
218    where
219        F: FnOnce(&OnceState),
220    {
221        // Fast path check
222        if self.inner.is_completed() {
223            return;
224        }
225
226        let mut f = Some(f);
227        self.inner.call(true, &mut |p| f.take().unwrap()(p));
228    }
229
230    /// Returns `true` if some [`call_once()`] call has completed
231    /// successfully. Specifically, `is_completed` will return false in
232    /// the following situations:
233    ///   * [`call_once()`] was not called at all,
234    ///   * [`call_once()`] was called, but has not yet completed,
235    ///   * the [`Once`] instance is poisoned
236    ///
237    /// This function returning `false` does not mean that [`Once`] has not been
238    /// executed. For example, it may have been executed in the time between
239    /// when `is_completed` starts executing and when it returns, in which case
240    /// the `false` return value would be stale (but still permissible).
241    ///
242    /// [`call_once()`]: Once::call_once
243    ///
244    /// # Examples
245    ///
246    /// ```
247    /// use std::sync::Once;
248    ///
249    /// static INIT: Once = Once::new();
250    ///
251    /// assert_eq!(INIT.is_completed(), false);
252    /// INIT.call_once(|| {
253    ///     assert_eq!(INIT.is_completed(), false);
254    /// });
255    /// assert_eq!(INIT.is_completed(), true);
256    /// ```
257    ///
258    /// ```
259    /// use std::sync::Once;
260    /// use std::thread;
261    ///
262    /// static INIT: Once = Once::new();
263    ///
264    /// assert_eq!(INIT.is_completed(), false);
265    /// let handle = thread::spawn(|| {
266    ///     INIT.call_once(|| panic!());
267    /// });
268    /// assert!(handle.join().is_err());
269    /// assert_eq!(INIT.is_completed(), false);
270    /// ```
271    #[stable(feature = "once_is_completed", since = "1.43.0")]
272    #[inline]
273    pub fn is_completed(&self) -> bool {
274        self.inner.is_completed()
275    }
276
277    /// Blocks the current thread until initialization has completed.
278    ///
279    /// # Example
280    ///
281    /// ```rust
282    /// use std::sync::Once;
283    /// use std::thread;
284    ///
285    /// static READY: Once = Once::new();
286    ///
287    /// let thread = thread::spawn(|| {
288    ///     READY.wait();
289    ///     println!("everything is ready");
290    /// });
291    ///
292    /// READY.call_once(|| println!("performing setup"));
293    /// ```
294    ///
295    /// # Panics
296    ///
297    /// If this [`Once`] has been poisoned because an initialization closure has
298    /// panicked, this method will also panic. Use [`wait_force`](Self::wait_force)
299    /// if this behavior is not desired.
300    #[inline]
301    #[stable(feature = "once_wait", since = "1.86.0")]
302    #[rustc_should_not_be_called_on_const_items]
303    pub fn wait(&self) {
304        if !self.inner.is_completed() {
305            self.inner.wait(false);
306        }
307    }
308
309    /// Blocks the current thread until initialization has completed, ignoring
310    /// poisoning.
311    ///
312    /// If this [`Once`] has been poisoned, this function blocks until it
313    /// becomes completed, unlike [`Once::wait()`], which panics in this case.
314    #[inline]
315    #[stable(feature = "once_wait", since = "1.86.0")]
316    #[rustc_should_not_be_called_on_const_items]
317    pub fn wait_force(&self) {
318        if !self.inner.is_completed() {
319            self.inner.wait(true);
320        }
321    }
322
323    /// Returns the current state of the `Once` instance.
324    ///
325    /// Since this takes a mutable reference, no initialization can currently
326    /// be running, so the state must be either "incomplete", "poisoned" or
327    /// "complete".
328    #[inline]
329    pub(crate) fn state(&mut self) -> OnceExclusiveState {
330        self.inner.state()
331    }
332
333    /// Sets current state of the `Once` instance.
334    ///
335    /// Since this takes a mutable reference, no initialization can currently
336    /// be running, so the state must be either "incomplete", "poisoned" or
337    /// "complete".
338    #[inline]
339    pub(crate) fn set_state(&mut self, new_state: OnceExclusiveState) {
340        self.inner.set_state(new_state);
341    }
342}
343
344#[stable(feature = "std_debug", since = "1.16.0")]
345impl fmt::Debug for Once {
346    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
347        f.debug_struct("Once").finish_non_exhaustive()
348    }
349}
350
351#[stable(feature = "once_default", since = "CURRENT_RUSTC_VERSION")]
352#[rustc_const_unstable(feature = "const_default", issue = "143894")]
353const impl Default for Once {
354    /// Creates a new `Once` value, same as [`Once::new`].
355    #[inline]
356    fn default() -> Once {
357        Once::new()
358    }
359}
360
361impl OnceState {
362    /// Returns `true` if the associated [`Once`] was poisoned prior to the
363    /// invocation of the closure passed to [`Once::call_once_force()`].
364    ///
365    /// # Examples
366    ///
367    /// A poisoned [`Once`]:
368    ///
369    /// ```
370    /// use std::sync::Once;
371    /// use std::thread;
372    ///
373    /// static INIT: Once = Once::new();
374    ///
375    /// // poison the once
376    /// let handle = thread::spawn(|| {
377    ///     INIT.call_once(|| panic!());
378    /// });
379    /// assert!(handle.join().is_err());
380    ///
381    /// INIT.call_once_force(|state| {
382    ///     assert!(state.is_poisoned());
383    /// });
384    /// ```
385    ///
386    /// An unpoisoned [`Once`]:
387    ///
388    /// ```
389    /// use std::sync::Once;
390    ///
391    /// static INIT: Once = Once::new();
392    ///
393    /// INIT.call_once_force(|state| {
394    ///     assert!(!state.is_poisoned());
395    /// });
396    #[stable(feature = "once_poison", since = "1.51.0")]
397    #[inline]
398    pub fn is_poisoned(&self) -> bool {
399        self.inner.is_poisoned()
400    }
401
402    /// Poison the associated [`Once`] without explicitly panicking.
403    // NOTE: This is currently only exposed for `OnceLock`.
404    #[inline]
405    pub(crate) fn poison(&self) {
406        self.inner.poison();
407    }
408}
409
410#[stable(feature = "std_debug", since = "1.16.0")]
411impl fmt::Debug for OnceState {
412    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413        f.debug_struct("OnceState").field("poisoned", &self.is_poisoned()).finish()
414    }
415}