rust/src/libsync/atomics.rs

231 lines
6.9 KiB
Rust
Raw Normal View History

// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2013-05-25 17:51:26 +12:00
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Atomic types
//!
//! Atomic types provide primitive shared-memory communication between
//! threads, and are the building blocks of other concurrent
//! types.
//!
//! This module defines atomic versions of a select number of primitive
//! types, including `AtomicBool`, `AtomicInt`, `AtomicUint`, and `AtomicOption`.
//! Atomic types present operations that, when used correctly, synchronize
//! updates between threads.
//!
//! Each method takes an `Ordering` which represents the strength of
//! the memory barrier for that operation. These orderings are the
//! same as [C++11 atomic orderings][1].
//!
//! [1]: http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync
//!
//! Atomic variables are safe to share between threads (they implement `Share`)
//! but they do not themselves provide the mechanism for sharing. The most
//! common way to share an atomic variable is to put it into an `Arc` (an
//! atomically-reference-counted shared pointer).
//!
//! Most atomic types may be stored in static variables, initialized using
//! the provided static initializers like `INIT_ATOMIC_BOOL`. Atomic statics
//! are often used for lazy global initialization.
//!
//!
//! # Examples
//!
//! A simple spinlock:
//!
2014-03-22 00:15:47 -07:00
//! ```
//! use std::sync::Arc;
//! use std::sync::atomics::{AtomicUint, SeqCst};
//! use std::task::deschedule;
//!
//! fn main() {
//! let spinlock = Arc::new(AtomicUint::new(1));
//!
//! let spinlock_clone = spinlock.clone();
//! spawn(proc() {
//! spinlock_clone.store(0, SeqCst);
//! });
//!
//! // Wait for the other task to release the lock
//! while spinlock.load(SeqCst) != 0 {
//! // Since tasks may not be preemptive (if they are green threads)
//! // yield to the scheduler to let the other task run. Low level
//! // concurrent code needs to take into account Rust's two threading
//! // models.
//! deschedule();
//! }
//! }
//! ```
//!
//! Transferring a heap object with `AtomicOption`:
//!
2014-03-22 00:15:47 -07:00
//! ```
//! use std::sync::Arc;
//! use std::sync::atomics::{AtomicOption, SeqCst};
//!
//! fn main() {
//! struct BigObject;
//!
//! let shared_big_object = Arc::new(AtomicOption::empty());
//!
//! let shared_big_object_clone = shared_big_object.clone();
//! spawn(proc() {
//! let unwrapped_big_object = shared_big_object_clone.take(SeqCst);
//! if unwrapped_big_object.is_some() {
//! println!("got a big object from another task");
//! } else {
//! println!("other task hasn't sent big object yet");
//! }
//! });
//!
//! shared_big_object.swap(box BigObject, SeqCst);
//! }
//! ```
//!
//! Keep a global count of live tasks:
//!
//! ```
//! use std::sync::atomics::{AtomicUint, SeqCst, INIT_ATOMIC_UINT};
//!
//! static mut GLOBAL_TASK_COUNT: AtomicUint = INIT_ATOMIC_UINT;
//!
//! unsafe {
//! let old_task_count = GLOBAL_TASK_COUNT.fetch_add(1, SeqCst);
//! println!("live tasks: {}", old_task_count + 1);
//! }
//! ```
2013-05-25 17:51:26 +12:00
use core::prelude::*;
use alloc::owned::Box;
use core::mem;
2013-05-25 17:51:26 +12:00
2014-05-12 21:30:48 -07:00
pub use core::atomics::{AtomicBool, AtomicInt, AtomicUint, AtomicPtr};
pub use core::atomics::{Ordering, Relaxed, Release, Acquire, AcqRel, SeqCst};
pub use core::atomics::{INIT_ATOMIC_BOOL, INIT_ATOMIC_INT, INIT_ATOMIC_UINT};
pub use core::atomics::fence;
2013-05-25 17:51:26 +12:00
/// An atomic, nullable unique pointer
///
/// This can be used as the concurrency primitive for operations that transfer
/// owned heap objects across tasks.
#[unsafe_no_drop_flag]
pub struct AtomicOption<T> {
2014-05-12 21:30:48 -07:00
p: AtomicUint,
2013-05-26 12:39:53 +12:00
}
impl<T> AtomicOption<T> {
/// Create a new `AtomicOption`
pub fn new(p: Box<T>) -> AtomicOption<T> {
2014-05-12 21:30:48 -07:00
unsafe { AtomicOption { p: AtomicUint::new(mem::transmute(p)) } }
2013-05-26 12:39:53 +12:00
}
/// Create a new `AtomicOption` that doesn't contain a value
2014-05-12 21:30:48 -07:00
pub fn empty() -> AtomicOption<T> { AtomicOption { p: AtomicUint::new(0) } }
2013-05-26 12:39:53 +12:00
/// Store a value, returning the old value
#[inline]
pub fn swap(&self, val: Box<T>, order: Ordering) -> Option<Box<T>> {
2014-05-12 21:30:48 -07:00
let val = unsafe { mem::transmute(val) };
2013-05-26 12:39:53 +12:00
2014-05-12 21:30:48 -07:00
match self.p.swap(val, order) {
0 => None,
n => Some(unsafe { mem::transmute(n) }),
2013-05-26 12:39:53 +12:00
}
}
/// Remove the value, leaving the `AtomicOption` empty.
#[inline]
pub fn take(&self, order: Ordering) -> Option<Box<T>> {
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 10:34:51 -07:00
unsafe { self.swap(mem::transmute(0), order) }
2013-05-26 12:39:53 +12:00
}
/// Replace an empty value with a non-empty value.
///
/// Succeeds if the option is `None` and returns `None` if so. If
/// the option was already `Some`, returns `Some` of the rejected
/// value.
#[inline]
pub fn fill(&self, val: Box<T>, order: Ordering) -> Option<Box<T>> {
unsafe {
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 10:34:51 -07:00
let val = mem::transmute(val);
let expected = mem::transmute(0);
2014-05-12 21:30:48 -07:00
let oldval = self.p.compare_and_swap(expected, val, order);
if oldval == expected {
None
} else {
core: Remove the cast module This commit revisits the `cast` module in libcore and libstd, and scrutinizes all functions inside of it. The result was to remove the `cast` module entirely, folding all functionality into the `mem` module. Specifically, this is the fate of each function in the `cast` module. * transmute - This function was moved to `mem`, but it is now marked as #[unstable]. This is due to planned changes to the `transmute` function and how it can be invoked (see the #[unstable] comment). For more information, see RFC 5 and #12898 * transmute_copy - This function was moved to `mem`, with clarification that is is not an error to invoke it with T/U that are different sizes, but rather that it is strongly discouraged. This function is now #[stable] * forget - This function was moved to `mem` and marked #[stable] * bump_box_refcount - This function was removed due to the deprecation of managed boxes as well as its questionable utility. * transmute_mut - This function was previously deprecated, and removed as part of this commit. * transmute_mut_unsafe - This function doesn't serve much of a purpose when it can be achieved with an `as` in safe code, so it was removed. * transmute_lifetime - This function was removed because it is likely a strong indication that code is incorrect in the first place. * transmute_mut_lifetime - This function was removed for the same reasons as `transmute_lifetime` * copy_lifetime - This function was moved to `mem`, but it is marked `#[unstable]` now due to the likelihood of being removed in the future if it is found to not be very useful. * copy_mut_lifetime - This function was also moved to `mem`, but had the same treatment as `copy_lifetime`. * copy_lifetime_vec - This function was removed because it is not used today, and its existence is not necessary with DST (copy_lifetime will suffice). In summary, the cast module was stripped down to these functions, and then the functions were moved to the `mem` module. transmute - #[unstable] transmute_copy - #[stable] forget - #[stable] copy_lifetime - #[unstable] copy_mut_lifetime - #[unstable] [breaking-change]
2014-05-09 10:34:51 -07:00
Some(mem::transmute(val))
}
}
}
/// Returns `true` if the `AtomicOption` is empty.
///
/// Be careful: The caller must have some external method of ensuring the
/// result does not get invalidated by another task after this returns.
#[inline]
pub fn is_empty(&self, order: Ordering) -> bool {
2014-05-12 21:30:48 -07:00
self.p.load(order) as uint == 0
}
2013-05-26 12:39:53 +12:00
}
#[unsafe_destructor]
impl<T> Drop for AtomicOption<T> {
2013-09-16 21:18:07 -04:00
fn drop(&mut self) {
2013-09-17 11:44:59 -04:00
let _ = self.take(SeqCst);
2013-05-25 17:51:26 +12:00
}
}
#[cfg(test)]
mod test {
use std::prelude::*;
2013-05-25 17:51:26 +12:00
use super::*;
#[test]
fn option_empty() {
let option: AtomicOption<()> = AtomicOption::empty();
assert!(option.is_empty(SeqCst));
}
2013-05-25 17:51:26 +12:00
#[test]
2013-05-26 12:39:53 +12:00
fn option_swap() {
let p = AtomicOption::new(box 1i);
let a = box 2i;
2013-05-25 17:51:26 +12:00
let b = p.swap(a, SeqCst);
2014-05-12 21:30:48 -07:00
assert!(b == Some(box 1));
assert!(p.take(SeqCst) == Some(box 2));
2013-05-25 17:51:26 +12:00
}
#[test]
2013-05-26 12:39:53 +12:00
fn option_take() {
let p = AtomicOption::new(box 1i);
2013-05-25 17:51:26 +12:00
2014-05-12 21:30:48 -07:00
assert!(p.take(SeqCst) == Some(box 1));
assert!(p.take(SeqCst) == None);
2013-05-25 17:51:26 +12:00
let p2 = box 2i;
2013-05-26 12:39:53 +12:00
p.swap(p2, SeqCst);
2013-05-25 17:51:26 +12:00
2014-05-12 21:30:48 -07:00
assert!(p.take(SeqCst) == Some(box 2));
2013-05-25 17:51:26 +12:00
}
#[test]
fn option_fill() {
let p = AtomicOption::new(box 1i);
assert!(p.fill(box 2i, SeqCst).is_some()); // should fail; shouldn't leak!
2014-05-12 21:30:48 -07:00
assert!(p.take(SeqCst) == Some(box 1));
assert!(p.fill(box 2i, SeqCst).is_none()); // shouldn't fail
2014-05-12 21:30:48 -07:00
assert!(p.take(SeqCst) == Some(box 2));
}
2013-05-25 17:51:26 +12:00
}
2014-05-12 21:30:48 -07:00