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