|
| 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 | +use sync::mutex::{StaticMutex, MUTEX_INIT}; |
| 19 | + |
| 20 | +/// A type which can be used to run a one-time global initialization. This type |
| 21 | +/// is *unsafe* to use because it is built on top of the `Mutex` in this module. |
| 22 | +/// It does not know whether the currently running task is in a green or native |
| 23 | +/// context, and a blocking mutex should *not* be used under normal |
| 24 | +/// circumstances on a green task. |
| 25 | +/// |
| 26 | +/// Despite its unsafety, it is often useful to have a one-time initialization |
| 27 | +/// routine run for FFI bindings or related external functionality. This type |
| 28 | +/// can only be statically constructed with the `ONCE_INIT` value. |
| 29 | +/// |
| 30 | +/// # Example |
| 31 | +/// |
| 32 | +/// ```rust |
| 33 | +/// use std::unstable::mutex::{Once, ONCE_INIT}; |
| 34 | +/// |
| 35 | +/// static mut START: Once = ONCE_INIT; |
| 36 | +/// unsafe { |
| 37 | +/// START.doit(|| { |
| 38 | +/// // run initialization here |
| 39 | +/// }); |
| 40 | +/// } |
| 41 | +/// ``` |
| 42 | +pub struct Once { |
| 43 | + priv mutex: StaticMutex, |
| 44 | + priv cnt: atomics::AtomicInt, |
| 45 | + priv lock_cnt: atomics::AtomicInt, |
| 46 | +} |
| 47 | + |
| 48 | +/// Initialization value for static `Once` values. |
| 49 | +pub static ONCE_INIT: Once = Once { |
| 50 | + mutex: MUTEX_INIT, |
| 51 | + cnt: atomics::INIT_ATOMIC_INT, |
| 52 | + lock_cnt: atomics::INIT_ATOMIC_INT, |
| 53 | +}; |
| 54 | + |
| 55 | +impl Once { |
| 56 | + /// Perform an initialization routine once and only once. The given closure |
| 57 | + /// will be executed if this is the first time `doit` has been called, and |
| 58 | + /// otherwise the routine will *not* be invoked. |
| 59 | + /// |
| 60 | + /// This method will block the calling *os thread* if another initialization |
| 61 | + /// routine is currently running. |
| 62 | + /// |
| 63 | + /// When this function returns, it is guaranteed that some initialization |
| 64 | + /// has run and completed (it may not be the closure specified). |
| 65 | + pub fn doit(&mut self, f: ||) { |
| 66 | + // Implementation-wise, this would seem like a fairly trivial primitive. |
| 67 | + // The stickler part is where our mutexes currently require an |
| 68 | + // allocation, and usage of a `Once` should't leak this allocation. |
| 69 | + // |
| 70 | + // This means that there must be a deterministic destroyer of the mutex |
| 71 | + // contained within (because it's not needed after the initialization |
| 72 | + // has run). |
| 73 | + // |
| 74 | + // The general scheme here is to gate all future threads once |
| 75 | + // initialization has completed with a "very negative" count, and to |
| 76 | + // allow through threads to lock the mutex if they see a non negative |
| 77 | + // count. For all threads grabbing the mutex, exactly one of them should |
| 78 | + // be responsible for unlocking the mutex, and this should only be done |
| 79 | + // once everyone else is done with the mutex. |
| 80 | + // |
| 81 | + // This atomicity is achieved by swapping a very negative value into the |
| 82 | + // shared count when the initialization routine has completed. This will |
| 83 | + // read the number of threads which will at some point attempt to |
| 84 | + // acquire the mutex. This count is then squirreled away in a separate |
| 85 | + // variable, and the last person on the way out of the mutex is then |
| 86 | + // responsible for destroying the mutex. |
| 87 | + // |
| 88 | + // It is crucial that the negative value is swapped in *after* the |
| 89 | + // initialization routine has completed because otherwise new threads |
| 90 | + // calling `doit` will return immediately before the initialization has |
| 91 | + // completed. |
| 92 | + |
| 93 | + let prev = self.cnt.fetch_add(1, atomics::SeqCst); |
| 94 | + if prev < 0 { |
| 95 | + // Make sure we never overflow, we'll never have int::MIN |
| 96 | + // simultaneous calls to `doit` to make this value go back to 0 |
| 97 | + self.cnt.store(int::MIN, atomics::SeqCst); |
| 98 | + return |
| 99 | + } |
| 100 | + |
| 101 | + // If the count is negative, then someone else finished the job, |
| 102 | + // otherwise we run the job and record how many people will try to grab |
| 103 | + // this lock |
| 104 | + { |
| 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 | + } |
| 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 (p, c) = SharedChan::new(); |
| 141 | + for _ in range(0, 10) { |
| 142 | + let c = c.clone(); |
| 143 | + do spawn { |
| 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 | + c.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 | + p.recv(); |
| 166 | + } |
| 167 | + } |
| 168 | +} |
0 commit comments