(index<- ) ./libsync/one.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Wed Apr 9 17:27:03 2014
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 std::int;
17 use std::sync::atomics;
18
19 use mutex::{StaticMutex, MUTEX_INIT};
20
21 /// A type which can be used to run a one-time global initialization. This type
22 /// is *unsafe* to use because it is built on top of the `Mutex` in this module.
23 /// It does not know whether the currently running task is in a green or native
24 /// context, and a blocking mutex should *not* be used under normal
25 /// circumstances on a green task.
26 ///
27 /// Despite its unsafety, it is often useful to have a one-time initialization
28 /// routine run for FFI bindings or related external functionality. This type
29 /// can only be statically constructed with the `ONCE_INIT` value.
30 ///
31 /// # Example
32 ///
33 /// ```rust
34 /// use sync::one::{Once, ONCE_INIT};
35 ///
36 /// static mut START: Once = ONCE_INIT;
37 /// unsafe {
38 /// START.doit(|| {
39 /// // run initialization here
40 /// });
41 /// }
42 /// ```
43 pub struct Once {
44 mutex: StaticMutex,
45 cnt: atomics::AtomicInt,
46 lock_cnt: atomics::AtomicInt,
47 }
48
49 /// Initialization value for static `Once` values.
50 pub static ONCE_INIT: Once = Once {
51 mutex: MUTEX_INIT,
52 cnt: atomics::INIT_ATOMIC_INT,
53 lock_cnt: atomics::INIT_ATOMIC_INT,
54 };
55
56 impl Once {
57 /// Perform an initialization routine once and only once. The given closure
58 /// will be executed if this is the first time `doit` has been called, and
59 /// otherwise the routine will *not* be invoked.
60 ///
61 /// This method will block the calling *os thread* if another initialization
62 /// routine is currently running.
63 ///
64 /// When this function returns, it is guaranteed that some initialization
65 /// has run and completed (it may not be the closure specified).
66 pub fn doit(&self, f: ||) {
67 // Implementation-wise, this would seem like a fairly trivial primitive.
68 // The stickler part is where our mutexes currently require an
69 // allocation, and usage of a `Once` should't leak this allocation.
70 //
71 // This means that there must be a deterministic destroyer of the mutex
72 // contained within (because it's not needed after the initialization
73 // has run).
74 //
75 // The general scheme here is to gate all future threads once
76 // initialization has completed with a "very negative" count, and to
77 // allow through threads to lock the mutex if they see a non negative
78 // count. For all threads grabbing the mutex, exactly one of them should
79 // be responsible for unlocking the mutex, and this should only be done
80 // once everyone else is done with the mutex.
81 //
82 // This atomicity is achieved by swapping a very negative value into the
83 // shared count when the initialization routine has completed. This will
84 // read the number of threads which will at some point attempt to
85 // acquire the mutex. This count is then squirreled away in a separate
86 // variable, and the last person on the way out of the mutex is then
87 // responsible for destroying the mutex.
88 //
89 // It is crucial that the negative value is swapped in *after* the
90 // initialization routine has completed because otherwise new threads
91 // calling `doit` will return immediately before the initialization has
92 // completed.
93
94 let prev = self.cnt.fetch_add(1, atomics::SeqCst);
95 if prev < 0 {
96 // Make sure we never overflow, we'll never have int::MIN
97 // simultaneous calls to `doit` to make this value go back to 0
98 self.cnt.store(int::MIN, atomics::SeqCst);
99 return
100 }
101
102 // If the count is negative, then someone else finished the job,
103 // otherwise we run the job and record how many people will try to grab
104 // this lock
105 let guard = self.mutex.lock();
106 if self.cnt.load(atomics::SeqCst) > 0 {
107 f();
108 let prev = self.cnt.swap(int::MIN, atomics::SeqCst);
109 self.lock_cnt.store(prev, atomics::SeqCst);
110 }
111 drop(guard);
112
113 // Last one out cleans up after everyone else, no leaks!
114 if self.lock_cnt.fetch_add(-1, atomics::SeqCst) == 1 {
115 unsafe { self.mutex.destroy() }
116 }
117 }
118 }
119
120 #[cfg(test)]
121 mod test {
122 use super::{ONCE_INIT, Once};
123 use std::task;
124
125 #[test]
126 fn smoke_once() {
127 static mut o: Once = ONCE_INIT;
128 let mut a = 0;
129 unsafe { o.doit(|| a += 1); }
130 assert_eq!(a, 1);
131 unsafe { o.doit(|| a += 1); }
132 assert_eq!(a, 1);
133 }
134
135 #[test]
136 fn stampede_once() {
137 static mut o: Once = ONCE_INIT;
138 static mut run: bool = false;
139
140 let (tx, rx) = channel();
141 for _ in range(0, 10) {
142 let tx = tx.clone();
143 spawn(proc() {
144 for _ in range(0, 4) { task::deschedule() }
145 unsafe {
146 o.doit(|| {
147 assert!(!run);
148 run = true;
149 });
150 assert!(run);
151 }
152 tx.send(());
153 });
154 }
155
156 unsafe {
157 o.doit(|| {
158 assert!(!run);
159 run = true;
160 });
161 assert!(run);
162 }
163
164 for _ in range(0, 10) {
165 rx.recv();
166 }
167 }
168 }