| 1 |
//! Synchronization primitives for one-time evaluation. |
| 2 |
|
| 3 |
use crate::{ |
| 4 |
atomic::{AtomicU8, Ordering}, |
| 5 |
RelaxStrategy, Spin, |
| 6 |
}; |
| 7 |
use core::{ |
| 8 |
cell::UnsafeCell, |
| 9 |
fmt, |
| 10 |
marker::PhantomData, |
| 11 |
mem::{ManuallyDrop, MaybeUninit}, |
| 12 |
}; |
| 13 |
|
| 14 |
/// A primitive that provides lazy one-time initialization. |
| 15 |
/// |
| 16 |
/// Unlike its `std::sync` equivalent, this is generalized such that the closure returns a |
| 17 |
/// value to be stored by the [`Once`] (`std::sync::Once` can be trivially emulated with |
| 18 |
/// `Once`). |
| 19 |
/// |
| 20 |
/// Because [`Once::new`] is `const`, this primitive may be used to safely initialize statics. |
| 21 |
/// |
| 22 |
/// # Examples |
| 23 |
/// |
| 24 |
/// ``` |
| 25 |
/// use spin; |
| 26 |
/// |
| 27 |
/// static START: spin::Once = spin::Once::new(); |
| 28 |
/// |
| 29 |
/// START.call_once(|| { |
| 30 |
/// // run initialization here |
| 31 |
/// }); |
| 32 |
/// ``` |
| 33 |
pub struct Once<T = (), R = Spin> { |
| 34 |
phantom: PhantomData<R>, |
| 35 |
status: AtomicStatus, |
| 36 |
data: UnsafeCell<MaybeUninit<T>>, |
| 37 |
} |
| 38 |
|
| 39 |
impl<T, R> Default for Once<T, R> { |
| 40 |
fn default() -> Self { |
| 41 |
Self::new() |
| 42 |
} |
| 43 |
} |
| 44 |
|
| 45 |
impl<T: fmt::Debug, R> fmt::Debug for Once<T, R> { |
| 46 |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { |
| 47 |
let mut d = f.debug_tuple("Once"); |
| 48 |
let d = if let Some(x) = self.get() { |
| 49 |
d.field(&x) |
| 50 |
} else { |
| 51 |
d.field(&format_args!("<uninit>")) |
| 52 |
}; |
| 53 |
d.finish() |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
// Same unsafe impls as `std::sync::RwLock`, because this also allows for |
| 58 |
// concurrent reads. |
| 59 |
unsafe impl<T: Send + Sync, R> Sync for Once<T, R> {} |
| 60 |
unsafe impl<T: Send, R> Send for Once<T, R> {} |
| 61 |
|
| 62 |
mod status { |
| 63 |
use super::*; |
| 64 |
|
| 65 |
// SAFETY: This structure has an invariant, namely that the inner atomic u8 must *always* have |
| 66 |
// a value for which there exists a valid Status. This means that users of this API must only |
| 67 |
// be allowed to load and store `Status`es. |
| 68 |
#[repr(transparent)] |
| 69 |
pub struct AtomicStatus(AtomicU8); |
| 70 |
|
| 71 |
// Four states that a Once can be in, encoded into the lower bits of `status` in |
| 72 |
// the Once structure. |
| 73 |
#[repr(u8)] |
| 74 |
#[derive(Clone, Copy, Debug, PartialEq)] |
| 75 |
pub enum Status { |
| 76 |
Incomplete = 0x00, |
| 77 |
Running = 0x01, |
| 78 |
Complete = 0x02, |
| 79 |
Panicked = 0x03, |
| 80 |
} |
| 81 |
impl Status { |
| 82 |
// Construct a status from an inner u8 integer. |
| 83 |
// |
| 84 |
// # Safety |
| 85 |
// |
| 86 |
// For this to be safe, the inner number must have a valid corresponding enum variant. |
| 87 |
unsafe fn new_unchecked(inner: u8) -> Self { |
| 88 |
core::mem::transmute(inner) |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
impl AtomicStatus { |
| 93 |
#[inline(always)] |
| 94 |
pub const fn new(status: Status) -> Self { |
| 95 |
// SAFETY: We got the value directly from status, so transmuting back is fine. |
| 96 |
Self(AtomicU8::new(status as u8)) |
| 97 |
} |
| 98 |
#[inline(always)] |
| 99 |
pub fn load(&self, ordering: Ordering) -> Status { |
| 100 |
// SAFETY: We know that the inner integer must have been constructed from a Status in |
| 101 |
// the first place. |
| 102 |
unsafe { Status::new_unchecked(self.0.load(ordering)) } |
| 103 |
} |
| 104 |
#[inline(always)] |
| 105 |
pub fn store(&self, status: Status, ordering: Ordering) { |
| 106 |
// SAFETY: While not directly unsafe, this is safe because the value was retrieved from |
| 107 |
// a status, thus making transmutation safe. |
| 108 |
self.0.store(status as u8, ordering); |
| 109 |
} |
| 110 |
#[inline(always)] |
| 111 |
pub fn compare_exchange( |
| 112 |
&self, |
| 113 |
old: Status, |
| 114 |
new: Status, |
| 115 |
success: Ordering, |
| 116 |
failure: Ordering, |
| 117 |
) -> Result<Status, Status> { |
| 118 |
match self |
| 119 |
.0 |
| 120 |
.compare_exchange(old as u8, new as u8, success, failure) |
| 121 |
{ |
| 122 |
// SAFETY: A compare exchange will always return a value that was later stored into |
| 123 |
// the atomic u8, but due to the invariant that it must be a valid Status, we know |
| 124 |
// that both Ok(_) and Err(_) will be safely transmutable. |
| 125 |
Ok(ok) => Ok(unsafe { Status::new_unchecked(ok) }), |
| 126 |
Err(err) => Err(unsafe { Status::new_unchecked(err) }), |
| 127 |
} |
| 128 |
} |
| 129 |
#[inline(always)] |
| 130 |
pub fn get_mut(&mut self) -> &mut Status { |
| 131 |
// SAFETY: Since we know that the u8 inside must be a valid Status, we can safely cast |
| 132 |
// it to a &mut Status. |
| 133 |
unsafe { &mut *((self.0.get_mut() as *mut u8).cast::<Status>()) } |
| 134 |
} |
| 135 |
} |
| 136 |
} |
| 137 |
use self::status::{AtomicStatus, Status}; |
| 138 |
|
| 139 |
impl<T, R: RelaxStrategy> Once<T, R> { |
| 140 |
/// Performs an initialization routine once and only once. The given closure |
| 141 |
/// will be executed if this is the first time `call_once` has been called, |
| 142 |
/// and otherwise the routine will *not* be invoked. |
| 143 |
/// |
| 144 |
/// This method will block the calling thread if another initialization |
| 145 |
/// routine is currently running. |
| 146 |
/// |
| 147 |
/// When this function returns, it is guaranteed that some initialization |
| 148 |
/// has run and completed (it may not be the closure specified). The |
| 149 |
/// returned pointer will point to the result from the closure that was |
| 150 |
/// run. |
| 151 |
/// |
| 152 |
/// # Panics |
| 153 |
/// |
| 154 |
/// This function will panic if the [`Once`] previously panicked while attempting |
| 155 |
/// to initialize. This is similar to the poisoning behaviour of `std::sync`'s |
| 156 |
/// primitives. |
| 157 |
/// |
| 158 |
/// # Examples |
| 159 |
/// |
| 160 |
/// ``` |
| 161 |
/// use spin; |
| 162 |
/// |
| 163 |
/// static INIT: spin::Once<usize> = spin::Once::new(); |
| 164 |
/// |
| 165 |
/// fn get_cached_val() -> usize { |
| 166 |
/// *INIT.call_once(expensive_computation) |
| 167 |
/// } |
| 168 |
/// |
| 169 |
/// fn expensive_computation() -> usize { |
| 170 |
/// // ... |
| 171 |
/// # 2 |
| 172 |
/// } |
| 173 |
/// ``` |
| 174 |
pub fn call_once<F: FnOnce() -> T>(&self, f: F) -> &T { |
| 175 |
match self.try_call_once(|| Ok::<T, core::convert::Infallible>(f())) { |
| 176 |
Ok(x) => x, |
| 177 |
Err(void) => match void {}, |
| 178 |
} |
| 179 |
} |
| 180 |
|
| 181 |
/// This method is similar to `call_once`, but allows the given closure to |
| 182 |
/// fail, and lets the `Once` in a uninitialized state if it does. |
| 183 |
/// |
| 184 |
/// This method will block the calling thread if another initialization |
| 185 |
/// routine is currently running. |
| 186 |
/// |
| 187 |
/// When this function returns without error, it is guaranteed that some |
| 188 |
/// initialization has run and completed (it may not be the closure |
| 189 |
/// specified). The returned reference will point to the result from the |
| 190 |
/// closure that was run. |
| 191 |
/// |
| 192 |
/// # Panics |
| 193 |
/// |
| 194 |
/// This function will panic if the [`Once`] previously panicked while attempting |
| 195 |
/// to initialize. This is similar to the poisoning behaviour of `std::sync`'s |
| 196 |
/// primitives. |
| 197 |
/// |
| 198 |
/// # Examples |
| 199 |
/// |
| 200 |
/// ``` |
| 201 |
/// use spin; |
| 202 |
/// |
| 203 |
/// static INIT: spin::Once<usize> = spin::Once::new(); |
| 204 |
/// |
| 205 |
/// fn get_cached_val() -> Result<usize, String> { |
| 206 |
/// INIT.try_call_once(expensive_fallible_computation).map(|x| *x) |
| 207 |
/// } |
| 208 |
/// |
| 209 |
/// fn expensive_fallible_computation() -> Result<usize, String> { |
| 210 |
/// // ... |
| 211 |
/// # Ok(2) |
| 212 |
/// } |
| 213 |
/// ``` |
| 214 |
pub fn try_call_once<F: FnOnce() -> Result<T, E>, E>(&self, f: F) -> Result<&T, E> { |
| 215 |
if let Some(value) = self.get() { |
| 216 |
Ok(value) |
| 217 |
} else { |
| 218 |
self.try_call_once_slow(f) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
#[cold] |
| 223 |
fn try_call_once_slow<F: FnOnce() -> Result<T, E>, E>(&self, f: F) -> Result<&T, E> { |
| 224 |
loop { |
| 225 |
let xchg = self.status.compare_exchange( |
| 226 |
Status::Incomplete, |
| 227 |
Status::Running, |
| 228 |
Ordering::Acquire, |
| 229 |
Ordering::Acquire, |
| 230 |
); |
| 231 |
|
| 232 |
match xchg { |
| 233 |
Ok(_must_be_state_incomplete) => { |
| 234 |
// Impl is defined after the match for readability |
| 235 |
} |
| 236 |
Err(Status::Panicked) => panic!("Once panicked"), |
| 237 |
Err(Status::Running) => match self.poll() { |
| 238 |
Some(v) => return Ok(v), |
| 239 |
None => continue, |
| 240 |
}, |
| 241 |
Err(Status::Complete) => { |
| 242 |
return Ok(unsafe { |
| 243 |
// SAFETY: The status is Complete |
| 244 |
self.force_get() |
| 245 |
}); |
| 246 |
} |
| 247 |
Err(Status::Incomplete) => { |
| 248 |
// The compare_exchange failed, so this shouldn't ever be reached, |
| 249 |
// however if we decide to switch to compare_exchange_weak it will |
| 250 |
// be safer to leave this here than hit an unreachable |
| 251 |
continue; |
| 252 |
} |
| 253 |
} |
| 254 |
|
| 255 |
// The compare-exchange succeeded, so we shall initialize it. |
| 256 |
|
| 257 |
// We use a guard (Finish) to catch panics caused by builder |
| 258 |
let finish = Finish { |
| 259 |
status: &self.status, |
| 260 |
}; |
| 261 |
let val = match f() { |
| 262 |
Ok(val) => val, |
| 263 |
Err(err) => { |
| 264 |
// If an error occurs, clean up everything and leave. |
| 265 |
core::mem::forget(finish); |
| 266 |
self.status.store(Status::Incomplete, Ordering::Release); |
| 267 |
return Err(err); |
| 268 |
} |
| 269 |
}; |
| 270 |
unsafe { |
| 271 |
// SAFETY: |
| 272 |
// `UnsafeCell`/deref: currently the only accessor, mutably |
| 273 |
// and immutably by cas exclusion. |
| 274 |
// `write`: pointer comes from `MaybeUninit`. |
| 275 |
(*self.data.get()).as_mut_ptr().write(val); |
| 276 |
}; |
| 277 |
// If there were to be a panic with unwind enabled, the code would |
| 278 |
// short-circuit and never reach the point where it writes the inner data. |
| 279 |
// The destructor for Finish will run, and poison the Once to ensure that other |
| 280 |
// threads accessing it do not exhibit unwanted behavior, if there were to be |
| 281 |
// any inconsistency in data structures caused by the panicking thread. |
| 282 |
// |
| 283 |
// However, f() is expected in the general case not to panic. In that case, we |
| 284 |
// simply forget the guard, bypassing its destructor. We could theoretically |
| 285 |
// clear a flag instead, but this eliminates the call to the destructor at |
| 286 |
// compile time, and unconditionally poisons during an eventual panic, if |
| 287 |
// unwinding is enabled. |
| 288 |
core::mem::forget(finish); |
| 289 |
|
| 290 |
// SAFETY: Release is required here, so that all memory accesses done in the |
| 291 |
// closure when initializing, become visible to other threads that perform Acquire |
| 292 |
// loads. |
| 293 |
// |
| 294 |
// And, we also know that the changes this thread has done will not magically |
| 295 |
// disappear from our cache, so it does not need to be AcqRel. |
| 296 |
self.status.store(Status::Complete, Ordering::Release); |
| 297 |
|
| 298 |
// This next line is mainly an optimization. |
| 299 |
return unsafe { Ok(self.force_get()) }; |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
/// Spins until the [`Once`] contains a value. |
| 304 |
/// |
| 305 |
/// Note that in releases prior to `0.7`, this function had the behaviour of [`Once::poll`]. |
| 306 |
/// |
| 307 |
/// # Panics |
| 308 |
/// |
| 309 |
/// This function will panic if the [`Once`] previously panicked while attempting |
| 310 |
/// to initialize. This is similar to the poisoning behaviour of `std::sync`'s |
| 311 |
/// primitives. |
| 312 |
pub fn wait(&self) -> &T { |
| 313 |
loop { |
| 314 |
match self.poll() { |
| 315 |
Some(x) => break x, |
| 316 |
None => R::relax(), |
| 317 |
} |
| 318 |
} |
| 319 |
} |
| 320 |
|
| 321 |
/// Like [`Once::get`], but will spin if the [`Once`] is in the process of being |
| 322 |
/// initialized. If initialization has not even begun, `None` will be returned. |
| 323 |
/// |
| 324 |
/// Note that in releases prior to `0.7`, this function was named `wait`. |
| 325 |
/// |
| 326 |
/// # Panics |
| 327 |
/// |
| 328 |
/// This function will panic if the [`Once`] previously panicked while attempting |
| 329 |
/// to initialize. This is similar to the poisoning behaviour of `std::sync`'s |
| 330 |
/// primitives. |
| 331 |
pub fn poll(&self) -> Option<&T> { |
| 332 |
loop { |
| 333 |
// SAFETY: Acquire is safe here, because if the status is COMPLETE, then we want to make |
| 334 |
// sure that all memory accessed done while initializing that value, are visible when |
| 335 |
// we return a reference to the inner data after this load. |
| 336 |
match self.status.load(Ordering::Acquire) { |
| 337 |
Status::Incomplete => return None, |
| 338 |
Status::Running => R::relax(), // We spin |
| 339 |
Status::Complete => return Some(unsafe { self.force_get() }), |
| 340 |
Status::Panicked => panic!("Once previously poisoned by a panicked"), |
| 341 |
} |
| 342 |
} |
| 343 |
} |
| 344 |
} |
| 345 |
|
| 346 |
impl<T, R> Once<T, R> { |
| 347 |
/// Initialization constant of [`Once`]. |
| 348 |
#[allow(clippy::declare_interior_mutable_const)] |
| 349 |
pub const INIT: Self = Self { |
| 350 |
phantom: PhantomData, |
| 351 |
status: AtomicStatus::new(Status::Incomplete), |
| 352 |
data: UnsafeCell::new(MaybeUninit::uninit()), |
| 353 |
}; |
| 354 |
|
| 355 |
/// Creates a new [`Once`]. |
| 356 |
pub const fn new() -> Self { |
| 357 |
Self::INIT |
| 358 |
} |
| 359 |
|
| 360 |
/// Creates a new initialized [`Once`]. |
| 361 |
pub const fn initialized(data: T) -> Self { |
| 362 |
Self { |
| 363 |
phantom: PhantomData, |
| 364 |
status: AtomicStatus::new(Status::Complete), |
| 365 |
data: UnsafeCell::new(MaybeUninit::new(data)), |
| 366 |
} |
| 367 |
} |
| 368 |
|
| 369 |
/// Retrieve a pointer to the inner data. |
| 370 |
/// |
| 371 |
/// While this method itself is safe, accessing the pointer before the [`Once`] has been |
| 372 |
/// initialized is UB, unless this method has already been written to from a pointer coming |
| 373 |
/// from this method. |
| 374 |
pub fn as_mut_ptr(&self) -> *mut T { |
| 375 |
// SAFETY: |
| 376 |
// * MaybeUninit<T> always has exactly the same layout as T |
| 377 |
self.data.get().cast::<T>() |
| 378 |
} |
| 379 |
|
| 380 |
/// Get a reference to the initialized instance. Must only be called once COMPLETE. |
| 381 |
unsafe fn force_get(&self) -> &T { |
| 382 |
// SAFETY: |
| 383 |
// * `UnsafeCell`/inner deref: data never changes again |
| 384 |
// * `MaybeUninit`/outer deref: data was initialized |
| 385 |
&*(*self.data.get()).as_ptr() |
| 386 |
} |
| 387 |
|
| 388 |
/// Get a reference to the initialized instance. Must only be called once COMPLETE. |
| 389 |
unsafe fn force_get_mut(&mut self) -> &mut T { |
| 390 |
// SAFETY: |
| 391 |
// * `UnsafeCell`/inner deref: data never changes again |
| 392 |
// * `MaybeUninit`/outer deref: data was initialized |
| 393 |
&mut *(*self.data.get()).as_mut_ptr() |
| 394 |
} |
| 395 |
|
| 396 |
/// Get a reference to the initialized instance. Must only be called once COMPLETE. |
| 397 |
unsafe fn force_into_inner(self) -> T { |
| 398 |
let mut this = ManuallyDrop::new(self); |
| 399 |
// SAFETY: |
| 400 |
// * `UnsafeCell`/inner deref: data never changes again |
| 401 |
// * `MaybeUninit`/outer deref: data was initialized |
| 402 |
// * We never call `self`'s destructor, ensuring a double-drop cannot occur. |
| 403 |
this.data.get_mut().assume_init_read() |
| 404 |
} |
| 405 |
|
| 406 |
/// Returns a reference to the inner value if the [`Once`] has been initialized. |
| 407 |
pub fn get(&self) -> Option<&T> { |
| 408 |
// SAFETY: Just as with `poll`, Acquire is safe here because we want to be able to see the |
| 409 |
// nonatomic stores done when initializing, once we have loaded and checked the status. |
| 410 |
match self.status.load(Ordering::Acquire) { |
| 411 |
Status::Complete => Some(unsafe { self.force_get() }), |
| 412 |
_ => None, |
| 413 |
} |
| 414 |
} |
| 415 |
|
| 416 |
/// Returns a reference to the inner value on the unchecked assumption that the [`Once`] has been initialized. |
| 417 |
/// |
| 418 |
/// # Safety |
| 419 |
/// |
| 420 |
/// This is *extremely* unsafe if the `Once` has not already been initialized because a reference to uninitialized |
| 421 |
/// memory will be returned, immediately triggering undefined behaviour (even if the reference goes unused). |
| 422 |
/// However, this can be useful in some instances for exposing the `Once` to FFI or when the overhead of atomically |
| 423 |
/// checking initialization is unacceptable and the `Once` has already been initialized. |
| 424 |
pub unsafe fn get_unchecked(&self) -> &T { |
| 425 |
debug_assert_eq!( |
| 426 |
self.status.load(Ordering::SeqCst), |
| 427 |
Status::Complete, |
| 428 |
"Attempted to access an uninitialized Once. If this was run without debug checks, this would be undefined behaviour. This is a serious bug and you must fix it.", |
| 429 |
); |
| 430 |
self.force_get() |
| 431 |
} |
| 432 |
|
| 433 |
/// Returns a mutable reference to the inner value if the [`Once`] has been initialized. |
| 434 |
/// |
| 435 |
/// Because this method requires a mutable reference to the [`Once`], no synchronization |
| 436 |
/// overhead is required to access the inner value. In effect, it is zero-cost. |
| 437 |
pub fn get_mut(&mut self) -> Option<&mut T> { |
| 438 |
match *self.status.get_mut() { |
| 439 |
Status::Complete => Some(unsafe { self.force_get_mut() }), |
| 440 |
_ => None, |
| 441 |
} |
| 442 |
} |
| 443 |
|
| 444 |
/// Returns a mutable reference to the inner value |
| 445 |
/// |
| 446 |
/// # Safety |
| 447 |
/// |
| 448 |
/// This is *extremely* unsafe if the `Once` has not already been initialized because a reference to uninitialized |
| 449 |
/// memory will be returned, immediately triggering undefined behaviour (even if the reference goes unused). |
| 450 |
/// However, this can be useful in some instances for exposing the `Once` to FFI or when the overhead of atomically |
| 451 |
/// checking initialization is unacceptable and the `Once` has already been initialized. |
| 452 |
pub unsafe fn get_mut_unchecked(&mut self) -> &mut T { |
| 453 |
debug_assert_eq!( |
| 454 |
self.status.load(Ordering::SeqCst), |
| 455 |
Status::Complete, |
| 456 |
"Attempted to access an unintialized Once. If this was to run without debug checks, this would be undefined behavior. This is a serious bug and you must fix it.", |
| 457 |
); |
| 458 |
self.force_get_mut() |
| 459 |
} |
| 460 |
|
| 461 |
/// Returns a the inner value if the [`Once`] has been initialized. |
| 462 |
/// |
| 463 |
/// Because this method requires ownership of the [`Once`], no synchronization overhead |
| 464 |
/// is required to access the inner value. In effect, it is zero-cost. |
| 465 |
pub fn try_into_inner(mut self) -> Option<T> { |
| 466 |
match *self.status.get_mut() { |
| 467 |
Status::Complete => Some(unsafe { self.force_into_inner() }), |
| 468 |
_ => None, |
| 469 |
} |
| 470 |
} |
| 471 |
|
| 472 |
/// Returns a the inner value if the [`Once`] has been initialized. |
| 473 |
/// # Safety |
| 474 |
/// |
| 475 |
/// This is *extremely* unsafe if the `Once` has not already been initialized because a reference to uninitialized |
| 476 |
/// memory will be returned, immediately triggering undefined behaviour (even if the reference goes unused) |
| 477 |
/// This can be useful, if `Once` has already been initialized, and you want to bypass an |
| 478 |
/// option check. |
| 479 |
pub unsafe fn into_inner_unchecked(self) -> T { |
| 480 |
debug_assert_eq!( |
| 481 |
self.status.load(Ordering::SeqCst), |
| 482 |
Status::Complete, |
| 483 |
"Attempted to access an unintialized Once. If this was to run without debug checks, this would be undefined behavior. This is a serious bug and you must fix it.", |
| 484 |
); |
| 485 |
self.force_into_inner() |
| 486 |
} |
| 487 |
|
| 488 |
/// Checks whether the value has been initialized. |
| 489 |
/// |
| 490 |
/// This is done using [`Acquire`](core::sync::atomic::Ordering::Acquire) ordering, and |
| 491 |
/// therefore it is safe to access the value directly via |
| 492 |
/// [`get_unchecked`](Self::get_unchecked) if this returns true. |
| 493 |
pub fn is_completed(&self) -> bool { |
| 494 |
// TODO: Add a similar variant for Relaxed? |
| 495 |
self.status.load(Ordering::Acquire) == Status::Complete |
| 496 |
} |
| 497 |
} |
| 498 |
|
| 499 |
impl<T, R> From<T> for Once<T, R> { |
| 500 |
fn from(data: T) -> Self { |
| 501 |
Self::initialized(data) |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
impl<T, R> Drop for Once<T, R> { |
| 506 |
fn drop(&mut self) { |
| 507 |
// No need to do any atomic access here, we have &mut! |
| 508 |
if *self.status.get_mut() == Status::Complete { |
| 509 |
unsafe { |
| 510 |
//TODO: Use MaybeUninit::assume_init_drop once stabilised |
| 511 |
core::ptr::drop_in_place((*self.data.get()).as_mut_ptr()); |
| 512 |
} |
| 513 |
} |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
struct Finish<'a> { |
| 518 |
status: &'a AtomicStatus, |
| 519 |
} |
| 520 |
|
| 521 |
impl<'a> Drop for Finish<'a> { |
| 522 |
fn drop(&mut self) { |
| 523 |
// While using Relaxed here would most likely not be an issue, we use SeqCst anyway. |
| 524 |
// This is mainly because panics are not meant to be fast at all, but also because if |
| 525 |
// there were to be a compiler bug which reorders accesses within the same thread, |
| 526 |
// where it should not, we want to be sure that the panic really is handled, and does |
| 527 |
// not cause additional problems. SeqCst will therefore help guarding against such |
| 528 |
// bugs. |
| 529 |
self.status.store(Status::Panicked, Ordering::SeqCst); |
| 530 |
} |
| 531 |
} |
| 532 |
|
| 533 |
#[cfg(test)] |
| 534 |
mod tests { |
| 535 |
use std::prelude::v1::*; |
| 536 |
|
| 537 |
use std::sync::atomic::AtomicU32; |
| 538 |
use std::sync::mpsc::channel; |
| 539 |
use std::sync::Arc; |
| 540 |
use std::thread; |
| 541 |
|
| 542 |
use super::*; |
| 543 |
|
| 544 |
#[test] |
| 545 |
fn smoke_once() { |
| 546 |
static O: Once = Once::new(); |
| 547 |
let mut a = 0; |
| 548 |
O.call_once(|| a += 1); |
| 549 |
assert_eq!(a, 1); |
| 550 |
O.call_once(|| a += 1); |
| 551 |
assert_eq!(a, 1); |
| 552 |
} |
| 553 |
|
| 554 |
#[test] |
| 555 |
fn smoke_once_value() { |
| 556 |
static O: Once<usize> = Once::new(); |
| 557 |
let a = O.call_once(|| 1); |
| 558 |
assert_eq!(*a, 1); |
| 559 |
let b = O.call_once(|| 2); |
| 560 |
assert_eq!(*b, 1); |
| 561 |
} |
| 562 |
|
| 563 |
#[test] |
| 564 |
fn stampede_once() { |
| 565 |
static O: Once = Once::new(); |
| 566 |
static mut RUN: bool = false; |
| 567 |
|
| 568 |
let (tx, rx) = channel(); |
| 569 |
let mut ts = Vec::new(); |
| 570 |
for _ in 0..10 { |
| 571 |
let tx = tx.clone(); |
| 572 |
ts.push(thread::spawn(move || { |
| 573 |
for _ in 0..4 { |
| 574 |
thread::yield_now() |
| 575 |
} |
| 576 |
unsafe { |
| 577 |
O.call_once(|| { |
| 578 |
assert!(!RUN); |
| 579 |
RUN = true; |
| 580 |
}); |
| 581 |
assert!(RUN); |
| 582 |
} |
| 583 |
tx.send(()).unwrap(); |
| 584 |
})); |
| 585 |
} |
| 586 |
|
| 587 |
unsafe { |
| 588 |
O.call_once(|| { |
| 589 |
assert!(!RUN); |
| 590 |
RUN = true; |
| 591 |
}); |
| 592 |
assert!(RUN); |
| 593 |
} |
| 594 |
|
| 595 |
for _ in 0..10 { |
| 596 |
rx.recv().unwrap(); |
| 597 |
} |
| 598 |
|
| 599 |
for t in ts { |
| 600 |
t.join().unwrap(); |
| 601 |
} |
| 602 |
} |
| 603 |
|
| 604 |
#[test] |
| 605 |
fn get() { |
| 606 |
static INIT: Once<usize> = Once::new(); |
| 607 |
|
| 608 |
assert!(INIT.get().is_none()); |
| 609 |
INIT.call_once(|| 2); |
| 610 |
assert_eq!(INIT.get().map(|r| *r), Some(2)); |
| 611 |
} |
| 612 |
|
| 613 |
#[test] |
| 614 |
fn get_no_wait() { |
| 615 |
static INIT: Once<usize> = Once::new(); |
| 616 |
|
| 617 |
assert!(INIT.get().is_none()); |
| 618 |
let t = thread::spawn(move || { |
| 619 |
INIT.call_once(|| { |
| 620 |
thread::sleep(std::time::Duration::from_secs(3)); |
| 621 |
42 |
| 622 |
}); |
| 623 |
}); |
| 624 |
assert!(INIT.get().is_none()); |
| 625 |
|
| 626 |
t.join().unwrap(); |
| 627 |
} |
| 628 |
|
| 629 |
#[test] |
| 630 |
fn poll() { |
| 631 |
static INIT: Once<usize> = Once::new(); |
| 632 |
|
| 633 |
assert!(INIT.poll().is_none()); |
| 634 |
INIT.call_once(|| 3); |
| 635 |
assert_eq!(INIT.poll().map(|r| *r), Some(3)); |
| 636 |
} |
| 637 |
|
| 638 |
#[test] |
| 639 |
fn wait() { |
| 640 |
static INIT: Once<usize> = Once::new(); |
| 641 |
|
| 642 |
let t = std::thread::spawn(|| { |
| 643 |
assert_eq!(*INIT.wait(), 3); |
| 644 |
assert!(INIT.is_completed()); |
| 645 |
}); |
| 646 |
|
| 647 |
for _ in 0..4 { |
| 648 |
thread::yield_now() |
| 649 |
} |
| 650 |
|
| 651 |
assert!(INIT.poll().is_none()); |
| 652 |
INIT.call_once(|| 3); |
| 653 |
|
| 654 |
t.join().unwrap(); |
| 655 |
} |
| 656 |
|
| 657 |
#[test] |
| 658 |
fn panic() { |
| 659 |
use std::panic; |
| 660 |
|
| 661 |
static INIT: Once = Once::new(); |
| 662 |
|
| 663 |
// poison the once |
| 664 |
let t = panic::catch_unwind(|| { |
| 665 |
INIT.call_once(|| panic!()); |
| 666 |
}); |
| 667 |
assert!(t.is_err()); |
| 668 |
|
| 669 |
// poisoning propagates |
| 670 |
let t = panic::catch_unwind(|| { |
| 671 |
INIT.call_once(|| {}); |
| 672 |
}); |
| 673 |
assert!(t.is_err()); |
| 674 |
} |
| 675 |
|
| 676 |
#[test] |
| 677 |
fn init_constant() { |
| 678 |
static O: Once = Once::INIT; |
| 679 |
let mut a = 0; |
| 680 |
O.call_once(|| a += 1); |
| 681 |
assert_eq!(a, 1); |
| 682 |
O.call_once(|| a += 1); |
| 683 |
assert_eq!(a, 1); |
| 684 |
} |
| 685 |
|
| 686 |
static mut CALLED: bool = false; |
| 687 |
|
| 688 |
struct DropTest {} |
| 689 |
|
| 690 |
impl Drop for DropTest { |
| 691 |
fn drop(&mut self) { |
| 692 |
unsafe { |
| 693 |
CALLED = true; |
| 694 |
} |
| 695 |
} |
| 696 |
} |
| 697 |
|
| 698 |
#[test] |
| 699 |
fn try_call_once_err() { |
| 700 |
let once = Once::<_, Spin>::new(); |
| 701 |
let shared = Arc::new((once, AtomicU32::new(0))); |
| 702 |
|
| 703 |
let (tx, rx) = channel(); |
| 704 |
|
| 705 |
let t0 = { |
| 706 |
let shared = shared.clone(); |
| 707 |
thread::spawn(move || { |
| 708 |
let (once, called) = &*shared; |
| 709 |
|
| 710 |
once.try_call_once(|| { |
| 711 |
called.fetch_add(1, Ordering::AcqRel); |
| 712 |
tx.send(()).unwrap(); |
| 713 |
thread::sleep(std::time::Duration::from_millis(50)); |
| 714 |
Err(()) |
| 715 |
}) |
| 716 |
.ok(); |
| 717 |
}) |
| 718 |
}; |
| 719 |
|
| 720 |
let t1 = { |
| 721 |
let shared = shared.clone(); |
| 722 |
thread::spawn(move || { |
| 723 |
rx.recv().unwrap(); |
| 724 |
let (once, called) = &*shared; |
| 725 |
assert_eq!( |
| 726 |
called.load(Ordering::Acquire), |
| 727 |
1, |
| 728 |
"leader thread did not run first" |
| 729 |
); |
| 730 |
|
| 731 |
once.call_once(|| { |
| 732 |
called.fetch_add(1, Ordering::AcqRel); |
| 733 |
}); |
| 734 |
}) |
| 735 |
}; |
| 736 |
|
| 737 |
t0.join().unwrap(); |
| 738 |
t1.join().unwrap(); |
| 739 |
|
| 740 |
assert_eq!(shared.1.load(Ordering::Acquire), 2); |
| 741 |
} |
| 742 |
|
| 743 |
// This is sort of two test cases, but if we write them as separate test methods |
| 744 |
// they can be executed concurrently and then fail some small fraction of the |
| 745 |
// time. |
| 746 |
#[test] |
| 747 |
fn drop_occurs_and_skip_uninit_drop() { |
| 748 |
unsafe { |
| 749 |
CALLED = false; |
| 750 |
} |
| 751 |
|
| 752 |
{ |
| 753 |
let once = Once::<_>::new(); |
| 754 |
once.call_once(|| DropTest {}); |
| 755 |
} |
| 756 |
|
| 757 |
assert!(unsafe { CALLED }); |
| 758 |
// Now test that we skip drops for the uninitialized case. |
| 759 |
unsafe { |
| 760 |
CALLED = false; |
| 761 |
} |
| 762 |
|
| 763 |
let once = Once::<DropTest>::new(); |
| 764 |
drop(once); |
| 765 |
|
| 766 |
assert!(unsafe { !CALLED }); |
| 767 |
} |
| 768 |
|
| 769 |
#[test] |
| 770 |
fn call_once_test() { |
| 771 |
for _ in 0..20 { |
| 772 |
use std::sync::atomic::AtomicUsize; |
| 773 |
use std::sync::Arc; |
| 774 |
use std::time::Duration; |
| 775 |
let share = Arc::new(AtomicUsize::new(0)); |
| 776 |
let once = Arc::new(Once::<_, Spin>::new()); |
| 777 |
let mut hs = Vec::new(); |
| 778 |
for _ in 0..8 { |
| 779 |
let h = thread::spawn({ |
| 780 |
let share = share.clone(); |
| 781 |
let once = once.clone(); |
| 782 |
move || { |
| 783 |
thread::sleep(Duration::from_millis(10)); |
| 784 |
once.call_once(|| { |
| 785 |
share.fetch_add(1, Ordering::SeqCst); |
| 786 |
}); |
| 787 |
} |
| 788 |
}); |
| 789 |
hs.push(h); |
| 790 |
} |
| 791 |
for h in hs { |
| 792 |
h.join().unwrap(); |
| 793 |
} |
| 794 |
assert_eq!(1, share.load(Ordering::SeqCst)); |
| 795 |
} |
| 796 |
} |
| 797 |
|
| 798 |
#[test] |
| 799 |
fn drop_boxed() { |
| 800 |
let boxed = Box::new(5); |
| 801 |
let once = Once::<_, Spin>::initialized(boxed); |
| 802 |
let boxed = once.try_into_inner().unwrap(); |
| 803 |
println!("{}", boxed); |
| 804 |
} |
| 805 |
} |