1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A "once initialization" primitive
13 //! This primitive is meant to be used to run one-time initialization. An
14 //! example use case would be for initializing an FFI library.
19 use sync::atomic::{AtomicIsize, Ordering, ATOMIC_ISIZE_INIT};
20 use sync::{StaticMutex, MUTEX_INIT};
22 /// A synchronization primitive which can be used to run a one-time global
23 /// initialization. Useful for one-time initialization for FFI or related
24 /// functionality. This type can only be constructed with the `ONCE_INIT`
30 /// use std::sync::{Once, ONCE_INIT};
32 /// static START: Once = ONCE_INIT;
34 /// START.call_once(|| {
35 /// // run initialization here
38 #[stable(feature = "rust1", since = "1.0.0")]
42 lock_cnt: AtomicIsize,
45 /// Initialization value for static `Once` values.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub const ONCE_INIT: Once = Once {
49 cnt: ATOMIC_ISIZE_INIT,
50 lock_cnt: ATOMIC_ISIZE_INIT,
54 /// Performs an initialization routine once and only once. The given closure
55 /// will be executed if this is the first time `call_once` has been called,
56 /// and otherwise the routine will *not* be invoked.
58 /// This method will block the calling task if another initialization
59 /// routine is currently running.
61 /// When this function returns, it is guaranteed that some initialization
62 /// has run and completed (it may not be the closure specified).
63 #[stable(feature = "rust1", since = "1.0.0")]
64 pub fn call_once<F>(&'static self, f: F) where F: FnOnce() {
65 // Optimize common path: load is much cheaper than fetch_add.
66 if self.cnt.load(Ordering::SeqCst) < 0 {
70 // Implementation-wise, this would seem like a fairly trivial primitive.
71 // The stickler part is where our mutexes currently require an
72 // allocation, and usage of a `Once` shouldn't leak this allocation.
74 // This means that there must be a deterministic destroyer of the mutex
75 // contained within (because it's not needed after the initialization
78 // The general scheme here is to gate all future threads once
79 // initialization has completed with a "very negative" count, and to
80 // allow through threads to lock the mutex if they see a non negative
81 // count. For all threads grabbing the mutex, exactly one of them should
82 // be responsible for unlocking the mutex, and this should only be done
83 // once everyone else is done with the mutex.
85 // This atomicity is achieved by swapping a very negative value into the
86 // shared count when the initialization routine has completed. This will
87 // read the number of threads which will at some point attempt to
88 // acquire the mutex. This count is then squirreled away in a separate
89 // variable, and the last person on the way out of the mutex is then
90 // responsible for destroying the mutex.
92 // It is crucial that the negative value is swapped in *after* the
93 // initialization routine has completed because otherwise new threads
94 // calling `call_once` will return immediately before the initialization
97 let prev = self.cnt.fetch_add(1, Ordering::SeqCst);
99 // Make sure we never overflow, we'll never have isize::MIN
100 // simultaneous calls to `call_once` to make this value go back to 0
101 self.cnt.store(isize::MIN, Ordering::SeqCst);
105 // If the count is negative, then someone else finished the job,
106 // otherwise we run the job and record how many people will try to grab
108 let guard = self.mutex.lock();
109 if self.cnt.load(Ordering::SeqCst) > 0 {
111 let prev = self.cnt.swap(isize::MIN, Ordering::SeqCst);
112 self.lock_cnt.store(prev, Ordering::SeqCst);
116 // Last one out cleans up after everyone else, no leaks!
117 if self.lock_cnt.fetch_add(-1, Ordering::SeqCst) == 1 {
118 unsafe { self.mutex.destroy() }
128 use super::{ONCE_INIT, Once};
129 use sync::mpsc::channel;
133 static O: Once = ONCE_INIT;
135 O.call_once(|| a += 1);
137 O.call_once(|| a += 1);
143 static O: Once = ONCE_INIT;
144 static mut run: bool = false;
146 let (tx, rx) = channel();
149 thread::spawn(move|| {
150 for _ in 0..4 { thread::yield_now() }
158 tx.send(()).unwrap();