]> git.proxmox.com Git - rustc.git/blob - src/libstd/sync/once.rs
57baedaad9c8e85fef351e66874347d6414a28ad
[rustc.git] / src / libstd / sync / once.rs
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.
4 //
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.
10
11 //! A "once initialization" primitive
12 //!
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.
15
16 use prelude::v1::*;
17
18 use isize;
19 use sync::atomic::{AtomicIsize, Ordering, ATOMIC_ISIZE_INIT};
20 use sync::{StaticMutex, MUTEX_INIT};
21
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`
25 /// value.
26 ///
27 /// # Examples
28 ///
29 /// ```
30 /// use std::sync::{Once, ONCE_INIT};
31 ///
32 /// static START: Once = ONCE_INIT;
33 ///
34 /// START.call_once(|| {
35 /// // run initialization here
36 /// });
37 /// ```
38 #[stable(feature = "rust1", since = "1.0.0")]
39 pub struct Once {
40 mutex: StaticMutex,
41 cnt: AtomicIsize,
42 lock_cnt: AtomicIsize,
43 }
44
45 /// Initialization value for static `Once` values.
46 #[stable(feature = "rust1", since = "1.0.0")]
47 pub const ONCE_INIT: Once = Once {
48 mutex: MUTEX_INIT,
49 cnt: ATOMIC_ISIZE_INIT,
50 lock_cnt: ATOMIC_ISIZE_INIT,
51 };
52
53 impl Once {
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.
57 ///
58 /// This method will block the calling thread if another initialization
59 /// routine is currently running.
60 ///
61 /// When this function returns, it is guaranteed that some initialization
62 /// has run and completed (it may not be the closure specified). It is also
63 /// guaranteed that any memory writes performed by the executed closure can
64 /// be reliably observed by other threads at this point (there is a
65 /// happens-before relation between the closure and code executing after the
66 /// return).
67 #[stable(feature = "rust1", since = "1.0.0")]
68 pub fn call_once<F>(&'static self, f: F) where F: FnOnce() {
69 // Optimize common path: load is much cheaper than fetch_add.
70 if self.cnt.load(Ordering::SeqCst) < 0 {
71 return
72 }
73
74 // Implementation-wise, this would seem like a fairly trivial primitive.
75 // The stickler part is where our mutexes currently require an
76 // allocation, and usage of a `Once` shouldn't leak this allocation.
77 //
78 // This means that there must be a deterministic destroyer of the mutex
79 // contained within (because it's not needed after the initialization
80 // has run).
81 //
82 // The general scheme here is to gate all future threads once
83 // initialization has completed with a "very negative" count, and to
84 // allow through threads to lock the mutex if they see a non negative
85 // count. For all threads grabbing the mutex, exactly one of them should
86 // be responsible for unlocking the mutex, and this should only be done
87 // once everyone else is done with the mutex.
88 //
89 // This atomicity is achieved by swapping a very negative value into the
90 // shared count when the initialization routine has completed. This will
91 // read the number of threads which will at some point attempt to
92 // acquire the mutex. This count is then squirreled away in a separate
93 // variable, and the last person on the way out of the mutex is then
94 // responsible for destroying the mutex.
95 //
96 // It is crucial that the negative value is swapped in *after* the
97 // initialization routine has completed because otherwise new threads
98 // calling `call_once` will return immediately before the initialization
99 // has completed.
100
101 let prev = self.cnt.fetch_add(1, Ordering::SeqCst);
102 if prev < 0 {
103 // Make sure we never overflow, we'll never have isize::MIN
104 // simultaneous calls to `call_once` to make this value go back to 0
105 self.cnt.store(isize::MIN, Ordering::SeqCst);
106 return
107 }
108
109 // If the count is negative, then someone else finished the job,
110 // otherwise we run the job and record how many people will try to grab
111 // this lock
112 let guard = self.mutex.lock();
113 if self.cnt.load(Ordering::SeqCst) > 0 {
114 f();
115 let prev = self.cnt.swap(isize::MIN, Ordering::SeqCst);
116 self.lock_cnt.store(prev, Ordering::SeqCst);
117 }
118 drop(guard);
119
120 // Last one out cleans up after everyone else, no leaks!
121 if self.lock_cnt.fetch_add(-1, Ordering::SeqCst) == 1 {
122 unsafe { self.mutex.destroy() }
123 }
124 }
125 }
126
127 #[cfg(test)]
128 mod tests {
129 use prelude::v1::*;
130
131 use thread;
132 use super::{ONCE_INIT, Once};
133 use sync::mpsc::channel;
134
135 #[test]
136 fn smoke_once() {
137 static O: Once = ONCE_INIT;
138 let mut a = 0;
139 O.call_once(|| a += 1);
140 assert_eq!(a, 1);
141 O.call_once(|| a += 1);
142 assert_eq!(a, 1);
143 }
144
145 #[test]
146 fn stampede_once() {
147 static O: Once = ONCE_INIT;
148 static mut run: bool = false;
149
150 let (tx, rx) = channel();
151 for _ in 0..10 {
152 let tx = tx.clone();
153 thread::spawn(move|| {
154 for _ in 0..4 { thread::yield_now() }
155 unsafe {
156 O.call_once(|| {
157 assert!(!run);
158 run = true;
159 });
160 assert!(run);
161 }
162 tx.send(()).unwrap();
163 });
164 }
165
166 unsafe {
167 O.call_once(|| {
168 assert!(!run);
169 run = true;
170 });
171 assert!(run);
172 }
173
174 for _ in 0..10 {
175 rx.recv().unwrap();
176 }
177 }
178 }