]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/once.rs
Auto merge of #94515 - estebank:tweak-move-error, r=davidtwco
[rust.git] / library / std / src / 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
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.
10 //
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!
15 //
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.
23 //
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.
28 //
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`:
32 //
33 // * Incomplete - no initialization has run yet, and no thread is currently
34 //                using the Once.
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
41 //             below.
42 // * Complete - initialization has completed and all future calls should finish
43 //              immediately.
44 //
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.
51 //
52 // You'll find a few more details in the implementation, but that's the gist of
53 // it!
54 //
55 // Atomic orderings:
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
63 //       three of them.
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
76 //       above.
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.
86
87 #[cfg(all(test, not(target_os = "emscripten")))]
88 mod tests;
89
90 use crate::cell::Cell;
91 use crate::fmt;
92 use crate::marker;
93 use crate::panic::{RefUnwindSafe, UnwindSafe};
94 use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
95 use crate::thread::{self, Thread};
96
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()`].
100 ///
101 /// # Examples
102 ///
103 /// ```
104 /// use std::sync::Once;
105 ///
106 /// static START: Once = Once::new();
107 ///
108 /// START.call_once(|| {
109 ///     // run initialization here
110 /// });
111 /// ```
112 #[stable(feature = "rust1", since = "1.0.0")]
113 pub struct Once {
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>,
118 }
119
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 {}
126
127 #[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
128 impl UnwindSafe for Once {}
129
130 #[stable(feature = "sync_once_unwind_safe", since = "1.59.0")]
131 impl RefUnwindSafe for Once {}
132
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")]
136 #[derive(Debug)]
137 pub struct OnceState {
138     poisoned: bool,
139     set_state_on_drop_to: Cell<usize>,
140 }
141
142 /// Initialization value for static [`Once`] values.
143 ///
144 /// # Examples
145 ///
146 /// ```
147 /// use std::sync::{Once, ONCE_INIT};
148 ///
149 /// static START: Once = ONCE_INIT;
150 /// ```
151 #[stable(feature = "rust1", since = "1.0.0")]
152 #[rustc_deprecated(
153     since = "1.38.0",
154     reason = "the `new` function is now preferred",
155     suggestion = "Once::new()"
156 )]
157 pub const ONCE_INIT: Once = Once::new();
158
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;
165
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;
169
170 // Representation of a node in the linked list of waiters, used while in the
171 // RUNNING state.
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.
177 struct Waiter {
178     thread: Cell<Option<Thread>>,
179     signaled: AtomicBool,
180     next: *const Waiter,
181 }
182
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,
189 }
190
191 impl Once {
192     /// Creates a new `Once` value.
193     #[inline]
194     #[stable(feature = "once_new", since = "1.2.0")]
195     #[rustc_const_stable(feature = "const_once_new", since = "1.32.0")]
196     #[must_use]
197     pub const fn new() -> Once {
198         Once { state_and_queue: AtomicUsize::new(INCOMPLETE), _marker: marker::PhantomData }
199     }
200
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.
204     ///
205     /// This method will block the calling thread if another initialization
206     /// routine is currently running.
207     ///
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
213     /// return).
214     ///
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.
218     ///
219     /// # Examples
220     ///
221     /// ```
222     /// use std::sync::Once;
223     ///
224     /// static mut VAL: usize = 0;
225     /// static INIT: Once = Once::new();
226     ///
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
229     /// // good to go!
230     /// //
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 {
234     ///     unsafe {
235     ///         INIT.call_once(|| {
236     ///             VAL = expensive_computation();
237     ///         });
238     ///         VAL
239     ///     }
240     /// }
241     ///
242     /// fn expensive_computation() -> usize {
243     ///     // ...
244     /// # 2
245     /// }
246     /// ```
247     ///
248     /// # Panics
249     ///
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.
254     ///
255     /// This is similar to [poisoning with mutexes][poison].
256     ///
257     /// [poison]: struct.Mutex.html#poisoning
258     #[stable(feature = "rust1", since = "1.0.0")]
259     #[track_caller]
260     pub fn call_once<F>(&self, f: F)
261     where
262         F: FnOnce(),
263     {
264         // Fast path check
265         if self.is_completed() {
266             return;
267         }
268
269         let mut f = Some(f);
270         self.call_inner(false, &mut |_| f.take().unwrap()());
271     }
272
273     /// Performs the same function as [`call_once()`] except ignores poisoning.
274     ///
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.
282     ///
283     /// The closure `f` is yielded a [`OnceState`] structure which can be used
284     /// to query the poison status of the [`Once`].
285     ///
286     /// [`call_once()`]: Once::call_once
287     /// [`call_once_force()`]: Once::call_once_force
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// use std::sync::Once;
293     /// use std::thread;
294     ///
295     /// static INIT: Once = Once::new();
296     ///
297     /// // poison the once
298     /// let handle = thread::spawn(|| {
299     ///     INIT.call_once(|| panic!());
300     /// });
301     /// assert!(handle.join().is_err());
302     ///
303     /// // poisoning propagates
304     /// let handle = thread::spawn(|| {
305     ///     INIT.call_once(|| {});
306     /// });
307     /// assert!(handle.join().is_err());
308     ///
309     /// // call_once_force will still run and reset the poisoned state
310     /// INIT.call_once_force(|state| {
311     ///     assert!(state.is_poisoned());
312     /// });
313     ///
314     /// // once any success happens, we stop propagating the poison
315     /// INIT.call_once(|| {});
316     /// ```
317     #[stable(feature = "once_poison", since = "1.51.0")]
318     pub fn call_once_force<F>(&self, f: F)
319     where
320         F: FnOnce(&OnceState),
321     {
322         // Fast path check
323         if self.is_completed() {
324             return;
325         }
326
327         let mut f = Some(f);
328         self.call_inner(true, &mut |p| f.take().unwrap()(p));
329     }
330
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
337     ///
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).
342     ///
343     /// [`call_once()`]: Once::call_once
344     ///
345     /// # Examples
346     ///
347     /// ```
348     /// use std::sync::Once;
349     ///
350     /// static INIT: Once = Once::new();
351     ///
352     /// assert_eq!(INIT.is_completed(), false);
353     /// INIT.call_once(|| {
354     ///     assert_eq!(INIT.is_completed(), false);
355     /// });
356     /// assert_eq!(INIT.is_completed(), true);
357     /// ```
358     ///
359     /// ```
360     /// use std::sync::Once;
361     /// use std::thread;
362     ///
363     /// static INIT: Once = Once::new();
364     ///
365     /// assert_eq!(INIT.is_completed(), false);
366     /// let handle = thread::spawn(|| {
367     ///     INIT.call_once(|| panic!());
368     /// });
369     /// assert!(handle.join().is_err());
370     /// assert_eq!(INIT.is_completed(), false);
371     /// ```
372     #[stable(feature = "once_is_completed", since = "1.43.0")]
373     #[inline]
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
380     }
381
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).
384     //
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
388     // in LLVM.
389     //
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.
393     #[cold]
394     #[track_caller]
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);
397         loop {
398             match state_and_queue {
399                 COMPLETE => break,
400                 POISONED if !ignore_poisoning => {
401                     // Panic to propagate the poison.
402                     panic!("Once instance has previously been poisoned");
403                 }
404                 POISONED | INCOMPLETE => {
405                     // Try to register this thread as the one RUNNING.
406                     let exchange_result = self.state_and_queue.compare_exchange(
407                         state_and_queue,
408                         RUNNING,
409                         Ordering::Acquire,
410                         Ordering::Acquire,
411                     );
412                     if let Err(old) = exchange_result {
413                         state_and_queue = old;
414                         continue;
415                     }
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,
421                     };
422                     // Run the initialization function, letting it know if we're
423                     // poisoned or not.
424                     let init_state = OnceState {
425                         poisoned: state_and_queue == POISONED,
426                         set_state_on_drop_to: Cell::new(COMPLETE),
427                     };
428                     init(&init_state);
429                     waiter_queue.set_state_on_drop_to = init_state.set_state_on_drop_to.get();
430                     break;
431                 }
432                 _ => {
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);
438                 }
439             }
440         }
441     }
442 }
443
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.
447     loop {
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 {
451             return;
452         }
453
454         // Create the node for our current thread.
455         let node = Waiter {
456             thread: Cell::new(Some(thread::current())),
457             signaled: AtomicBool::new(false),
458             next: (current_state & !STATE_MASK) as *const Waiter,
459         };
460         let me = &node as *const Waiter as usize;
461
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(
465             current_state,
466             me | RUNNING,
467             Ordering::Release,
468             Ordering::Relaxed,
469         );
470         if let Err(old) = exchange_result {
471             current_state = old;
472             continue;
473         }
474
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.
485             thread::park();
486         }
487         break;
488     }
489 }
490
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()
495     }
496 }
497
498 impl Drop for WaiterQueue<'_> {
499     fn drop(&mut self) {
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);
503
504         // We should only ever see an old state which was RUNNING.
505         assert_eq!(state_and_queue & STATE_MASK, RUNNING);
506
507         // Walk the entire linked list of waiters and wake them up (in lifo
508         // order, last to register is first to wake up).
509         unsafe {
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
513             // `next` first.
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`.
521                 queue = next;
522                 thread.unpark();
523             }
524         }
525     }
526 }
527
528 impl OnceState {
529     /// Returns `true` if the associated [`Once`] was poisoned prior to the
530     /// invocation of the closure passed to [`Once::call_once_force()`].
531     ///
532     /// # Examples
533     ///
534     /// A poisoned [`Once`]:
535     ///
536     /// ```
537     /// use std::sync::Once;
538     /// use std::thread;
539     ///
540     /// static INIT: Once = Once::new();
541     ///
542     /// // poison the once
543     /// let handle = thread::spawn(|| {
544     ///     INIT.call_once(|| panic!());
545     /// });
546     /// assert!(handle.join().is_err());
547     ///
548     /// INIT.call_once_force(|state| {
549     ///     assert!(state.is_poisoned());
550     /// });
551     /// ```
552     ///
553     /// An unpoisoned [`Once`]:
554     ///
555     /// ```
556     /// use std::sync::Once;
557     ///
558     /// static INIT: Once = Once::new();
559     ///
560     /// INIT.call_once_force(|state| {
561     ///     assert!(!state.is_poisoned());
562     /// });
563     #[stable(feature = "once_poison", since = "1.51.0")]
564     pub fn is_poisoned(&self) -> bool {
565         self.poisoned
566     }
567
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);
572     }
573 }