auto merge of #12900 : alexcrichton/rust/rewrite-sync, r=brson
* Remove clone-ability from all primitives. All shared state will now come from the usage of the primitives being shared, not the primitives being inherently shareable. This allows for fewer allocations for stack-allocated primitives. * Add `Mutex<T>` and `RWLock<T>` which are stack-allocated primitives for purely wrapping a piece of data * Remove `RWArc<T>` in favor of `Arc<RWLock<T>>` * Remove `MutexArc<T>` in favor of `Arc<Mutex<T>>` * Shuffle around where things are located * The `arc` module now only contains `Arc` * A new `lock` module contains `Mutex`, `RWLock`, and `Barrier` * A new `raw` module contains the primitive implementations of `Semaphore`, `Mutex`, and `RWLock` * The Deref/DerefMut trait was implemented where appropriate * `CowArc` was removed, the functionality is now part of `Arc` and is tagged with `#[experimental]`. * The crate now has #[deny(missing_doc)] * `Arc` now supports weak pointers This is not a large-scale rewrite of the functionality contained within the `sync` crate, but rather a shuffling of who does what an a thinner hierarchy of ownership to allow for better composability.
This commit is contained in:
commit
6bf3fca8ff
48 changed files with 1738 additions and 2045 deletions
|
@ -12,7 +12,6 @@
|
|||
#[feature(phase)];
|
||||
|
||||
#[allow(non_camel_case_types)];
|
||||
#[allow(deprecated_owned_vector)]; // NOTE: remove after stage0
|
||||
#[deny(warnings)];
|
||||
|
||||
extern crate test;
|
||||
|
|
|
@ -359,7 +359,7 @@ fn main() {
|
|||
|
||||
spawn(proc() {
|
||||
let local_arc : Arc<~[f64]> = rx.recv();
|
||||
let task_numbers = local_arc.get();
|
||||
let task_numbers = &*local_arc;
|
||||
println!("{}-norm = {}", num, pnorm(task_numbers, num));
|
||||
});
|
||||
}
|
||||
|
@ -411,7 +411,7 @@ Each task recovers the underlying data by
|
|||
# let (tx, rx) = channel();
|
||||
# tx.send(numbers_arc.clone());
|
||||
# let local_arc : Arc<~[f64]> = rx.recv();
|
||||
let task_numbers = local_arc.get();
|
||||
let task_numbers = &*local_arc;
|
||||
# }
|
||||
~~~
|
||||
|
||||
|
|
|
@ -14,9 +14,4 @@ extern crate this = "rustdoc";
|
|||
#[cfg(rustc)]
|
||||
extern crate this = "rustc";
|
||||
|
||||
#[cfg(not(stage0))]
|
||||
fn main() { this::main() }
|
||||
|
||||
#[cfg(stage0)]
|
||||
#[start]
|
||||
fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, this::main) }
|
||||
|
|
|
@ -41,7 +41,7 @@ exceptions = [
|
|||
"libstd/sync/mpsc_queue.rs", # BSD
|
||||
"libstd/sync/spsc_queue.rs", # BSD
|
||||
"libstd/sync/mpmc_bounded_queue.rs", # BSD
|
||||
"libsync/sync/mpsc_intrusive.rs", # BSD
|
||||
"libsync/mpsc_intrusive.rs", # BSD
|
||||
]
|
||||
|
||||
def check_license(name, contents):
|
||||
|
|
|
@ -207,16 +207,6 @@ pub mod sleeper_list;
|
|||
pub mod stack;
|
||||
pub mod task;
|
||||
|
||||
#[lang = "start"]
|
||||
#[cfg(not(test), stage0)]
|
||||
pub fn lang_start(main: *u8, argc: int, argv: **u8) -> int {
|
||||
use std::cast;
|
||||
start(argc, argv, proc() {
|
||||
let main: extern "Rust" fn() = unsafe { cast::transmute(main) };
|
||||
main();
|
||||
})
|
||||
}
|
||||
|
||||
/// Set up a default runtime configuration, given compiler-supplied arguments.
|
||||
///
|
||||
/// This function will block until the entire pool of M:N schedulers have
|
||||
|
|
|
@ -40,7 +40,7 @@ impl Runtime for SimpleTask {
|
|||
// See libnative/task.rs for what's going on here with the `awoken`
|
||||
// field and the while loop around wait()
|
||||
unsafe {
|
||||
let mut guard = (*me).lock.lock();
|
||||
let guard = (*me).lock.lock();
|
||||
(*me).awoken = false;
|
||||
match f(task) {
|
||||
Ok(()) => {
|
||||
|
@ -60,7 +60,7 @@ impl Runtime for SimpleTask {
|
|||
to_wake.put_runtime(self as ~Runtime);
|
||||
unsafe {
|
||||
cast::forget(to_wake);
|
||||
let mut guard = (*me).lock.lock();
|
||||
let guard = (*me).lock.lock();
|
||||
(*me).awoken = true;
|
||||
guard.signal();
|
||||
}
|
||||
|
|
|
@ -75,7 +75,7 @@ pub fn send(req: Req) {
|
|||
fn shutdown() {
|
||||
// Request a shutdown, and then wait for the task to exit
|
||||
unsafe {
|
||||
let mut guard = TIMER_HELPER_EXIT.lock();
|
||||
let guard = TIMER_HELPER_EXIT.lock();
|
||||
send(Shutdown);
|
||||
guard.wait();
|
||||
drop(guard);
|
||||
|
|
|
@ -69,7 +69,7 @@ static OS_DEFAULT_STACK_ESTIMATE: uint = 1 << 20;
|
|||
static OS_DEFAULT_STACK_ESTIMATE: uint = 2 * (1 << 20);
|
||||
|
||||
#[lang = "start"]
|
||||
#[cfg(not(test), not(stage0))]
|
||||
#[cfg(not(test))]
|
||||
pub fn lang_start(main: *u8, argc: int, argv: **u8) -> int {
|
||||
use std::cast;
|
||||
start(argc, argv, proc() {
|
||||
|
|
|
@ -190,7 +190,7 @@ impl rt::Runtime for Ops {
|
|||
let task = BlockedTask::block(cur_task);
|
||||
|
||||
if times == 1 {
|
||||
let mut guard = (*me).lock.lock();
|
||||
let guard = (*me).lock.lock();
|
||||
(*me).awoken = false;
|
||||
match f(task) {
|
||||
Ok(()) => {
|
||||
|
@ -202,7 +202,7 @@ impl rt::Runtime for Ops {
|
|||
}
|
||||
} else {
|
||||
let mut iter = task.make_selectable(times);
|
||||
let mut guard = (*me).lock.lock();
|
||||
let guard = (*me).lock.lock();
|
||||
(*me).awoken = false;
|
||||
let success = iter.all(|task| {
|
||||
match f(task) {
|
||||
|
@ -232,7 +232,7 @@ impl rt::Runtime for Ops {
|
|||
let me = &mut *self as *mut Ops;
|
||||
to_wake.put_runtime(self as ~rt::Runtime);
|
||||
cast::forget(to_wake);
|
||||
let mut guard = (*me).lock.lock();
|
||||
let guard = (*me).lock.lock();
|
||||
(*me).awoken = true;
|
||||
guard.signal();
|
||||
}
|
||||
|
|
|
@ -208,8 +208,8 @@ fn path(w: &mut io::Writer, path: &clean::Path, print_all: bool,
|
|||
let loc = loc.unwrap();
|
||||
|
||||
local_data::get(cache_key, |cache| {
|
||||
let cache = cache.unwrap().get();
|
||||
let abs_root = root(cache, loc.as_slice());
|
||||
let cache = cache.unwrap();
|
||||
let abs_root = root(&**cache, loc.as_slice());
|
||||
let rel_root = match path.segments.get(0).name.as_slice() {
|
||||
"self" => Some(~"./"),
|
||||
_ => None,
|
||||
|
@ -241,7 +241,7 @@ fn path(w: &mut io::Writer, path: &clean::Path, print_all: bool,
|
|||
}
|
||||
}
|
||||
|
||||
match info(cache) {
|
||||
match info(&**cache) {
|
||||
// This is a documented path, link to it!
|
||||
Some((ref fqp, shortty)) if abs_root.is_some() => {
|
||||
let mut url = abs_root.unwrap();
|
||||
|
@ -301,7 +301,7 @@ impl fmt::Show for clean::Type {
|
|||
match *self {
|
||||
clean::TyParamBinder(id) | clean::Generic(id) => {
|
||||
local_data::get(cache_key, |cache| {
|
||||
let m = cache.unwrap().get();
|
||||
let m = cache.unwrap();
|
||||
f.buf.write(m.typarams.get(&id).as_bytes())
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1265,7 +1265,7 @@ fn item_trait(w: &mut Writer, it: &clean::Item,
|
|||
}
|
||||
|
||||
local_data::get(cache_key, |cache| {
|
||||
let cache = cache.unwrap().get();
|
||||
let cache = cache.unwrap();
|
||||
match cache.implementors.find(&it.id) {
|
||||
Some(implementors) => {
|
||||
try!(write!(w, "
|
||||
|
@ -1496,7 +1496,7 @@ fn render_struct(w: &mut Writer, it: &clean::Item,
|
|||
|
||||
fn render_methods(w: &mut Writer, it: &clean::Item) -> fmt::Result {
|
||||
local_data::get(cache_key, |cache| {
|
||||
let c = cache.unwrap().get();
|
||||
let c = cache.unwrap();
|
||||
match c.impls.find(&it.id) {
|
||||
Some(v) => {
|
||||
let mut non_trait = v.iter().filter(|p| {
|
||||
|
@ -1576,7 +1576,7 @@ fn render_impl(w: &mut Writer, i: &clean::Impl,
|
|||
Some(id) => id,
|
||||
};
|
||||
try!(local_data::get(cache_key, |cache| {
|
||||
let cache = cache.unwrap().get();
|
||||
let cache = cache.unwrap();
|
||||
match cache.traits.find(&trait_id) {
|
||||
Some(t) => {
|
||||
let name = meth.name.clone();
|
||||
|
@ -1606,7 +1606,7 @@ fn render_impl(w: &mut Writer, i: &clean::Impl,
|
|||
None => {}
|
||||
Some(id) => {
|
||||
try!(local_data::get(cache_key, |cache| {
|
||||
let cache = cache.unwrap().get();
|
||||
let cache = cache.unwrap();
|
||||
match cache.traits.find(&id) {
|
||||
Some(t) => {
|
||||
for method in t.methods.iter() {
|
||||
|
|
|
@ -68,7 +68,7 @@ pub enum Failure {
|
|||
impl<T: Send> Packet<T> {
|
||||
// Creation of a packet *must* be followed by a call to inherit_blocker
|
||||
pub fn new() -> Packet<T> {
|
||||
let mut p = Packet {
|
||||
let p = Packet {
|
||||
queue: mpsc::Queue::new(),
|
||||
cnt: atomics::AtomicInt::new(0),
|
||||
steals: 0,
|
||||
|
|
|
@ -164,7 +164,6 @@ pub trait TyVisitor {
|
|||
fn visit_self(&mut self) -> bool;
|
||||
}
|
||||
|
||||
|
||||
extern "rust-intrinsic" {
|
||||
|
||||
// NB: These intrinsics take unsafe pointers because they mutate aliased
|
||||
|
|
|
@ -34,7 +34,7 @@ pub fn increment() {
|
|||
pub fn decrement() {
|
||||
unsafe {
|
||||
if TASK_COUNT.fetch_sub(1, atomics::SeqCst) == 1 {
|
||||
let mut guard = TASK_LOCK.lock();
|
||||
let guard = TASK_LOCK.lock();
|
||||
guard.signal();
|
||||
}
|
||||
}
|
||||
|
@ -44,7 +44,7 @@ pub fn decrement() {
|
|||
/// the entry points of native programs
|
||||
pub fn wait_for_other_tasks() {
|
||||
unsafe {
|
||||
let mut guard = TASK_LOCK.lock();
|
||||
let guard = TASK_LOCK.lock();
|
||||
while TASK_COUNT.load(atomics::SeqCst) > 0 {
|
||||
guard.wait();
|
||||
}
|
||||
|
|
|
@ -39,8 +39,7 @@
|
|||
//!
|
||||
//! A simple spinlock:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! # // FIXME: Needs PR #12430
|
||||
//! ```
|
||||
//! extern crate sync;
|
||||
//!
|
||||
//! use sync::Arc;
|
||||
|
@ -68,8 +67,7 @@
|
|||
//!
|
||||
//! Transferring a heap object with `AtomicOption`:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! # // FIXME: Needs PR #12430
|
||||
//! ```
|
||||
//! extern crate sync;
|
||||
//!
|
||||
//! use sync::Arc;
|
||||
|
|
|
@ -86,7 +86,7 @@ pub struct NativeMutex {
|
|||
/// then.
|
||||
#[must_use]
|
||||
pub struct LockGuard<'a> {
|
||||
priv lock: &'a mut StaticNativeMutex
|
||||
priv lock: &'a StaticNativeMutex
|
||||
}
|
||||
|
||||
pub static NATIVE_MUTEX_INIT: StaticNativeMutex = StaticNativeMutex {
|
||||
|
@ -106,6 +106,7 @@ impl StaticNativeMutex {
|
|||
/// already hold the lock.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```rust
|
||||
/// use std::unstable::mutex::{StaticNativeMutex, NATIVE_MUTEX_INIT};
|
||||
/// static mut LOCK: StaticNativeMutex = NATIVE_MUTEX_INIT;
|
||||
|
@ -114,7 +115,7 @@ impl StaticNativeMutex {
|
|||
/// // critical section...
|
||||
/// } // automatically unlocked in `_guard`'s destructor
|
||||
/// ```
|
||||
pub unsafe fn lock<'a>(&'a mut self) -> LockGuard<'a> {
|
||||
pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
|
||||
self.inner.lock();
|
||||
|
||||
LockGuard { lock: self }
|
||||
|
@ -122,7 +123,7 @@ impl StaticNativeMutex {
|
|||
|
||||
/// Attempts to acquire the lock. The value returned is `Some` if
|
||||
/// the attempt succeeded.
|
||||
pub unsafe fn trylock<'a>(&'a mut self) -> Option<LockGuard<'a>> {
|
||||
pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
|
||||
if self.inner.trylock() {
|
||||
Some(LockGuard { lock: self })
|
||||
} else {
|
||||
|
@ -134,7 +135,7 @@ impl StaticNativeMutex {
|
|||
///
|
||||
/// These needs to be paired with a call to `.unlock_noguard`. Prefer using
|
||||
/// `.lock`.
|
||||
pub unsafe fn lock_noguard(&mut self) { self.inner.lock() }
|
||||
pub unsafe fn lock_noguard(&self) { self.inner.lock() }
|
||||
|
||||
/// Attempts to acquire the lock without creating a
|
||||
/// `LockGuard`. The value returned is whether the lock was
|
||||
|
@ -142,28 +143,28 @@ impl StaticNativeMutex {
|
|||
///
|
||||
/// If `true` is returned, this needs to be paired with a call to
|
||||
/// `.unlock_noguard`. Prefer using `.trylock`.
|
||||
pub unsafe fn trylock_noguard(&mut self) -> bool {
|
||||
pub unsafe fn trylock_noguard(&self) -> bool {
|
||||
self.inner.trylock()
|
||||
}
|
||||
|
||||
/// Unlocks the lock. This assumes that the current thread already holds the
|
||||
/// lock.
|
||||
pub unsafe fn unlock_noguard(&mut self) { self.inner.unlock() }
|
||||
pub unsafe fn unlock_noguard(&self) { self.inner.unlock() }
|
||||
|
||||
/// Block on the internal condition variable.
|
||||
///
|
||||
/// This function assumes that the lock is already held. Prefer
|
||||
/// using `LockGuard.wait` since that guarantees that the lock is
|
||||
/// held.
|
||||
pub unsafe fn wait_noguard(&mut self) { self.inner.wait() }
|
||||
pub unsafe fn wait_noguard(&self) { self.inner.wait() }
|
||||
|
||||
/// Signals a thread in `wait` to wake up
|
||||
pub unsafe fn signal_noguard(&mut self) { self.inner.signal() }
|
||||
pub unsafe fn signal_noguard(&self) { self.inner.signal() }
|
||||
|
||||
/// This function is especially unsafe because there are no guarantees made
|
||||
/// that no other thread is currently holding the lock or waiting on the
|
||||
/// condition variable contained inside.
|
||||
pub unsafe fn destroy(&mut self) { self.inner.destroy() }
|
||||
pub unsafe fn destroy(&self) { self.inner.destroy() }
|
||||
}
|
||||
|
||||
impl NativeMutex {
|
||||
|
@ -190,13 +191,13 @@ impl NativeMutex {
|
|||
/// } // automatically unlocked in `_guard`'s destructor
|
||||
/// }
|
||||
/// ```
|
||||
pub unsafe fn lock<'a>(&'a mut self) -> LockGuard<'a> {
|
||||
pub unsafe fn lock<'a>(&'a self) -> LockGuard<'a> {
|
||||
self.inner.lock()
|
||||
}
|
||||
|
||||
/// Attempts to acquire the lock. The value returned is `Some` if
|
||||
/// the attempt succeeded.
|
||||
pub unsafe fn trylock<'a>(&'a mut self) -> Option<LockGuard<'a>> {
|
||||
pub unsafe fn trylock<'a>(&'a self) -> Option<LockGuard<'a>> {
|
||||
self.inner.trylock()
|
||||
}
|
||||
|
||||
|
@ -204,7 +205,7 @@ impl NativeMutex {
|
|||
///
|
||||
/// These needs to be paired with a call to `.unlock_noguard`. Prefer using
|
||||
/// `.lock`.
|
||||
pub unsafe fn lock_noguard(&mut self) { self.inner.lock_noguard() }
|
||||
pub unsafe fn lock_noguard(&self) { self.inner.lock_noguard() }
|
||||
|
||||
/// Attempts to acquire the lock without creating a
|
||||
/// `LockGuard`. The value returned is whether the lock was
|
||||
|
@ -212,23 +213,23 @@ impl NativeMutex {
|
|||
///
|
||||
/// If `true` is returned, this needs to be paired with a call to
|
||||
/// `.unlock_noguard`. Prefer using `.trylock`.
|
||||
pub unsafe fn trylock_noguard(&mut self) -> bool {
|
||||
pub unsafe fn trylock_noguard(&self) -> bool {
|
||||
self.inner.trylock_noguard()
|
||||
}
|
||||
|
||||
/// Unlocks the lock. This assumes that the current thread already holds the
|
||||
/// lock.
|
||||
pub unsafe fn unlock_noguard(&mut self) { self.inner.unlock_noguard() }
|
||||
pub unsafe fn unlock_noguard(&self) { self.inner.unlock_noguard() }
|
||||
|
||||
/// Block on the internal condition variable.
|
||||
///
|
||||
/// This function assumes that the lock is already held. Prefer
|
||||
/// using `LockGuard.wait` since that guarantees that the lock is
|
||||
/// held.
|
||||
pub unsafe fn wait_noguard(&mut self) { self.inner.wait_noguard() }
|
||||
pub unsafe fn wait_noguard(&self) { self.inner.wait_noguard() }
|
||||
|
||||
/// Signals a thread in `wait` to wake up
|
||||
pub unsafe fn signal_noguard(&mut self) { self.inner.signal_noguard() }
|
||||
pub unsafe fn signal_noguard(&self) { self.inner.signal_noguard() }
|
||||
}
|
||||
|
||||
impl Drop for NativeMutex {
|
||||
|
@ -239,12 +240,12 @@ impl Drop for NativeMutex {
|
|||
|
||||
impl<'a> LockGuard<'a> {
|
||||
/// Block on the internal condition variable.
|
||||
pub unsafe fn wait(&mut self) {
|
||||
pub unsafe fn wait(&self) {
|
||||
self.lock.wait_noguard()
|
||||
}
|
||||
|
||||
/// Signals a thread in `wait` to wake up.
|
||||
pub unsafe fn signal(&mut self) {
|
||||
pub unsafe fn signal(&self) {
|
||||
self.lock.signal_noguard()
|
||||
}
|
||||
}
|
||||
|
@ -262,6 +263,8 @@ mod imp {
|
|||
use self::os::{PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER,
|
||||
pthread_mutex_t, pthread_cond_t};
|
||||
use mem;
|
||||
use ty::Unsafe;
|
||||
use kinds::marker;
|
||||
|
||||
type pthread_mutexattr_t = libc::c_void;
|
||||
type pthread_condattr_t = libc::c_void;
|
||||
|
@ -369,40 +372,46 @@ mod imp {
|
|||
}
|
||||
|
||||
pub struct Mutex {
|
||||
priv lock: pthread_mutex_t,
|
||||
priv cond: pthread_cond_t,
|
||||
priv lock: Unsafe<pthread_mutex_t>,
|
||||
priv cond: Unsafe<pthread_cond_t>,
|
||||
}
|
||||
|
||||
pub static MUTEX_INIT: Mutex = Mutex {
|
||||
lock: PTHREAD_MUTEX_INITIALIZER,
|
||||
cond: PTHREAD_COND_INITIALIZER,
|
||||
lock: Unsafe {
|
||||
value: PTHREAD_MUTEX_INITIALIZER,
|
||||
marker1: marker::InvariantType,
|
||||
},
|
||||
cond: Unsafe {
|
||||
value: PTHREAD_COND_INITIALIZER,
|
||||
marker1: marker::InvariantType,
|
||||
},
|
||||
};
|
||||
|
||||
impl Mutex {
|
||||
pub unsafe fn new() -> Mutex {
|
||||
let mut m = Mutex {
|
||||
lock: mem::init(),
|
||||
cond: mem::init(),
|
||||
let m = Mutex {
|
||||
lock: Unsafe::new(mem::init()),
|
||||
cond: Unsafe::new(mem::init()),
|
||||
};
|
||||
|
||||
pthread_mutex_init(&mut m.lock, 0 as *libc::c_void);
|
||||
pthread_cond_init(&mut m.cond, 0 as *libc::c_void);
|
||||
pthread_mutex_init(m.lock.get(), 0 as *libc::c_void);
|
||||
pthread_cond_init(m.cond.get(), 0 as *libc::c_void);
|
||||
|
||||
return m;
|
||||
}
|
||||
|
||||
pub unsafe fn lock(&mut self) { pthread_mutex_lock(&mut self.lock); }
|
||||
pub unsafe fn unlock(&mut self) { pthread_mutex_unlock(&mut self.lock); }
|
||||
pub unsafe fn signal(&mut self) { pthread_cond_signal(&mut self.cond); }
|
||||
pub unsafe fn wait(&mut self) {
|
||||
pthread_cond_wait(&mut self.cond, &mut self.lock);
|
||||
pub unsafe fn lock(&self) { pthread_mutex_lock(self.lock.get()); }
|
||||
pub unsafe fn unlock(&self) { pthread_mutex_unlock(self.lock.get()); }
|
||||
pub unsafe fn signal(&self) { pthread_cond_signal(self.cond.get()); }
|
||||
pub unsafe fn wait(&self) {
|
||||
pthread_cond_wait(self.cond.get(), self.lock.get());
|
||||
}
|
||||
pub unsafe fn trylock(&mut self) -> bool {
|
||||
pthread_mutex_trylock(&mut self.lock) == 0
|
||||
pub unsafe fn trylock(&self) -> bool {
|
||||
pthread_mutex_trylock(self.lock.get()) == 0
|
||||
}
|
||||
pub unsafe fn destroy(&mut self) {
|
||||
pthread_mutex_destroy(&mut self.lock);
|
||||
pthread_cond_destroy(&mut self.cond);
|
||||
pub unsafe fn destroy(&self) {
|
||||
pthread_mutex_destroy(self.lock.get());
|
||||
pthread_cond_destroy(self.cond.get());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -454,37 +463,37 @@ mod imp {
|
|||
cond: atomics::AtomicUint::new(init_cond()),
|
||||
}
|
||||
}
|
||||
pub unsafe fn lock(&mut self) {
|
||||
pub unsafe fn lock(&self) {
|
||||
EnterCriticalSection(self.getlock() as LPCRITICAL_SECTION)
|
||||
}
|
||||
pub unsafe fn trylock(&mut self) -> bool {
|
||||
pub unsafe fn trylock(&self) -> bool {
|
||||
TryEnterCriticalSection(self.getlock() as LPCRITICAL_SECTION) != 0
|
||||
}
|
||||
pub unsafe fn unlock(&mut self) {
|
||||
pub unsafe fn unlock(&self) {
|
||||
LeaveCriticalSection(self.getlock() as LPCRITICAL_SECTION)
|
||||
}
|
||||
|
||||
pub unsafe fn wait(&mut self) {
|
||||
pub unsafe fn wait(&self) {
|
||||
self.unlock();
|
||||
WaitForSingleObject(self.getcond() as HANDLE, libc::INFINITE);
|
||||
self.lock();
|
||||
}
|
||||
|
||||
pub unsafe fn signal(&mut self) {
|
||||
pub unsafe fn signal(&self) {
|
||||
assert!(SetEvent(self.getcond() as HANDLE) != 0);
|
||||
}
|
||||
|
||||
/// This function is especially unsafe because there are no guarantees made
|
||||
/// that no other thread is currently holding the lock or waiting on the
|
||||
/// condition variable contained inside.
|
||||
pub unsafe fn destroy(&mut self) {
|
||||
pub unsafe fn destroy(&self) {
|
||||
let lock = self.lock.swap(0, atomics::SeqCst);
|
||||
let cond = self.cond.swap(0, atomics::SeqCst);
|
||||
if lock != 0 { free_lock(lock) }
|
||||
if cond != 0 { free_cond(cond) }
|
||||
}
|
||||
|
||||
unsafe fn getlock(&mut self) -> *mut c_void {
|
||||
unsafe fn getlock(&self) -> *mut c_void {
|
||||
match self.lock.load(atomics::SeqCst) {
|
||||
0 => {}
|
||||
n => return n as *mut c_void
|
||||
|
@ -498,7 +507,7 @@ mod imp {
|
|||
return self.lock.load(atomics::SeqCst) as *mut c_void;
|
||||
}
|
||||
|
||||
unsafe fn getcond(&mut self) -> *mut c_void {
|
||||
unsafe fn getcond(&self) -> *mut c_void {
|
||||
match self.cond.load(atomics::SeqCst) {
|
||||
0 => {}
|
||||
n => return n as *mut c_void
|
||||
|
|
|
@ -79,7 +79,7 @@ impl<T:Send> Exclusive<T> {
|
|||
#[inline]
|
||||
pub unsafe fn hold_and_signal(&self, f: |x: &mut T|) {
|
||||
let rec = self.x.get();
|
||||
let mut guard = (*rec).lock.lock();
|
||||
let guard = (*rec).lock.lock();
|
||||
if (*rec).failed {
|
||||
fail!("Poisoned Exclusive::new - another task failed inside!");
|
||||
}
|
||||
|
@ -92,7 +92,7 @@ impl<T:Send> Exclusive<T> {
|
|||
#[inline]
|
||||
pub unsafe fn hold_and_wait(&self, f: |x: &T| -> bool) {
|
||||
let rec = self.x.get();
|
||||
let mut l = (*rec).lock.lock();
|
||||
let l = (*rec).lock.lock();
|
||||
if (*rec).failed {
|
||||
fail!("Poisoned Exclusive::new - another task failed inside!");
|
||||
}
|
||||
|
|
1182
src/libsync/arc.rs
1182
src/libsync/arc.rs
File diff suppressed because it is too large
Load diff
|
@ -20,18 +20,28 @@
|
|||
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
|
||||
html_root_url = "http://static.rust-lang.org/doc/master")];
|
||||
#[feature(phase)];
|
||||
#[deny(missing_doc, deprecated_owned_vector)];
|
||||
|
||||
#[cfg(test)] #[phase(syntax, link)] extern crate log;
|
||||
#[cfg(test)]
|
||||
#[phase(syntax, link)] extern crate log;
|
||||
|
||||
pub use arc::{Arc, MutexArc, RWArc, RWWriteMode, RWReadMode, ArcCondvar, CowArc};
|
||||
pub use sync::{Mutex, RWLock, Condvar, Semaphore, RWLockWriteMode,
|
||||
RWLockReadMode, Barrier, one, mutex};
|
||||
pub use comm::{DuplexStream, SyncSender, SyncReceiver, rendezvous, duplex};
|
||||
pub use task_pool::TaskPool;
|
||||
pub use future::Future;
|
||||
pub use arc::{Arc, Weak};
|
||||
pub use lock::{Mutex, MutexGuard, Condvar, Barrier,
|
||||
RWLock, RWLockReadGuard, RWLockWriteGuard};
|
||||
|
||||
// The mutex/rwlock in this module are not meant for reexport
|
||||
pub use raw::{Semaphore, SemaphoreGuard};
|
||||
|
||||
mod arc;
|
||||
mod sync;
|
||||
mod comm;
|
||||
mod task_pool;
|
||||
mod future;
|
||||
mod lock;
|
||||
mod mpsc_intrusive;
|
||||
mod task_pool;
|
||||
|
||||
pub mod raw;
|
||||
pub mod mutex;
|
||||
pub mod one;
|
||||
|
|
816
src/libsync/lock.rs
Normal file
816
src/libsync/lock.rs
Normal file
|
@ -0,0 +1,816 @@
|
|||
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
//! Wrappers for safe, shared, mutable memory between tasks
|
||||
//!
|
||||
//! The wrappers in this module build on the primitives from `sync::raw` to
|
||||
//! provide safe interfaces around using the primitive locks. These primitives
|
||||
//! implement a technique called "poisoning" where when a task failed with a
|
||||
//! held lock, all future attempts to use the lock will fail.
|
||||
//!
|
||||
//! For example, if two tasks are contending on a mutex and one of them fails
|
||||
//! after grabbing the lock, the second task will immediately fail because the
|
||||
//! lock is now poisoned.
|
||||
|
||||
use std::task;
|
||||
use std::ty::Unsafe;
|
||||
|
||||
use raw;
|
||||
|
||||
/****************************************************************************
|
||||
* Poisoning helpers
|
||||
****************************************************************************/
|
||||
|
||||
struct PoisonOnFail<'a> {
|
||||
flag: &'a mut bool,
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl<'a> PoisonOnFail<'a> {
|
||||
fn check(flag: bool, name: &str) {
|
||||
if flag {
|
||||
fail!("Poisoned {} - another task failed inside!", name);
|
||||
}
|
||||
}
|
||||
|
||||
fn new<'a>(flag: &'a mut bool, name: &str) -> PoisonOnFail<'a> {
|
||||
PoisonOnFail::check(*flag, name);
|
||||
PoisonOnFail {
|
||||
flag: flag,
|
||||
failed: task::failing()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe_destructor]
|
||||
impl<'a> Drop for PoisonOnFail<'a> {
|
||||
fn drop(&mut self) {
|
||||
if !self.failed && task::failing() {
|
||||
*self.flag = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/****************************************************************************
|
||||
* Condvar
|
||||
****************************************************************************/
|
||||
|
||||
enum Inner<'a> {
|
||||
InnerMutex(raw::MutexGuard<'a>),
|
||||
InnerRWLock(raw::RWLockWriteGuard<'a>),
|
||||
}
|
||||
|
||||
impl<'b> Inner<'b> {
|
||||
fn cond<'a>(&'a self) -> &'a raw::Condvar<'b> {
|
||||
match *self {
|
||||
InnerMutex(ref m) => &m.cond,
|
||||
InnerRWLock(ref m) => &m.cond,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A condition variable, a mechanism for unlock-and-descheduling and
|
||||
/// signaling, for use with the lock types.
|
||||
pub struct Condvar<'a> {
|
||||
priv name: &'static str,
|
||||
// n.b. Inner must be after PoisonOnFail because we must set the poison flag
|
||||
// *inside* the mutex, and struct fields are destroyed top-to-bottom
|
||||
// (destroy the lock guard last).
|
||||
priv poison: PoisonOnFail<'a>,
|
||||
priv inner: Inner<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Condvar<'a> {
|
||||
/// Atomically exit the associated lock and block until a signal is sent.
|
||||
///
|
||||
/// wait() is equivalent to wait_on(0).
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
/// A task which is killed while waiting on a condition variable will wake
|
||||
/// up, fail, and unlock the associated lock as it unwinds.
|
||||
#[inline]
|
||||
pub fn wait(&self) { self.wait_on(0) }
|
||||
|
||||
/// Atomically exit the associated lock and block on a specified condvar
|
||||
/// until a signal is sent on that same condvar.
|
||||
///
|
||||
/// The associated lock must have been initialised with an appropriate
|
||||
/// number of condvars. The condvar_id must be between 0 and num_condvars-1
|
||||
/// or else this call will fail.
|
||||
#[inline]
|
||||
pub fn wait_on(&self, condvar_id: uint) {
|
||||
assert!(!*self.poison.flag);
|
||||
self.inner.cond().wait_on(condvar_id);
|
||||
// This is why we need to wrap sync::condvar.
|
||||
PoisonOnFail::check(*self.poison.flag, self.name);
|
||||
}
|
||||
|
||||
/// Wake up a blocked task. Returns false if there was no blocked task.
|
||||
#[inline]
|
||||
pub fn signal(&self) -> bool { self.signal_on(0) }
|
||||
|
||||
/// Wake up a blocked task on a specified condvar (as
|
||||
/// sync::cond.signal_on). Returns false if there was no blocked task.
|
||||
#[inline]
|
||||
pub fn signal_on(&self, condvar_id: uint) -> bool {
|
||||
assert!(!*self.poison.flag);
|
||||
self.inner.cond().signal_on(condvar_id)
|
||||
}
|
||||
|
||||
/// Wake up all blocked tasks. Returns the number of tasks woken.
|
||||
#[inline]
|
||||
pub fn broadcast(&self) -> uint { self.broadcast_on(0) }
|
||||
|
||||
/// Wake up all blocked tasks on a specified condvar (as
|
||||
/// sync::cond.broadcast_on). Returns the number of tasks woken.
|
||||
#[inline]
|
||||
pub fn broadcast_on(&self, condvar_id: uint) -> uint {
|
||||
assert!(!*self.poison.flag);
|
||||
self.inner.cond().broadcast_on(condvar_id)
|
||||
}
|
||||
}
|
||||
|
||||
/****************************************************************************
|
||||
* Mutex
|
||||
****************************************************************************/
|
||||
|
||||
/// A wrapper type which provides synchronized access to the underlying data, of
|
||||
/// type `T`. A mutex always provides exclusive access, and concurrent requests
|
||||
/// will block while the mutex is already locked.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use sync::{Mutex, Arc};
|
||||
///
|
||||
/// let mutex = Arc::new(Mutex::new(1));
|
||||
/// let mutex2 = mutex.clone();
|
||||
///
|
||||
/// spawn(proc() {
|
||||
/// let mut val = mutex2.lock();
|
||||
/// *val += 1;
|
||||
/// val.cond.signal();
|
||||
/// });
|
||||
///
|
||||
/// let mut value = mutex.lock();
|
||||
/// while *value != 2 {
|
||||
/// value.cond.wait();
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Mutex<T> {
|
||||
priv lock: raw::Mutex,
|
||||
priv failed: Unsafe<bool>,
|
||||
priv data: Unsafe<T>,
|
||||
}
|
||||
|
||||
/// An guard which is created by locking a mutex. Through this guard the
|
||||
/// underlying data can be accessed.
|
||||
pub struct MutexGuard<'a, T> {
|
||||
priv data: &'a mut T,
|
||||
/// Inner condition variable connected to the locked mutex that this guard
|
||||
/// was created from. This can be used for atomic-unlock-and-deschedule.
|
||||
cond: Condvar<'a>,
|
||||
}
|
||||
|
||||
impl<T: Send> Mutex<T> {
|
||||
/// Creates a new mutex to protect the user-supplied data.
|
||||
pub fn new(user_data: T) -> Mutex<T> {
|
||||
Mutex::new_with_condvars(user_data, 1)
|
||||
}
|
||||
|
||||
/// Create a new mutex, with a specified number of associated condvars.
|
||||
///
|
||||
/// This will allow calling wait_on/signal_on/broadcast_on with condvar IDs
|
||||
/// between 0 and num_condvars-1. (If num_condvars is 0, lock_cond will be
|
||||
/// allowed but any operations on the condvar will fail.)
|
||||
pub fn new_with_condvars(user_data: T, num_condvars: uint) -> Mutex<T> {
|
||||
Mutex {
|
||||
lock: raw::Mutex::new_with_condvars(num_condvars),
|
||||
failed: Unsafe::new(false),
|
||||
data: Unsafe::new(user_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the underlying mutable data with mutual exclusion from other
|
||||
/// tasks. The returned value is an RAII guard which will unlock the mutex
|
||||
/// when dropped. All concurrent tasks attempting to lock the mutex will
|
||||
/// block while the returned value is still alive.
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
/// Failing while inside the Mutex will unlock the Mutex while unwinding, so
|
||||
/// that other tasks won't block forever. It will also poison the Mutex:
|
||||
/// any tasks that subsequently try to access it (including those already
|
||||
/// blocked on the mutex) will also fail immediately.
|
||||
#[inline]
|
||||
pub fn lock<'a>(&'a self) -> MutexGuard<'a, T> {
|
||||
let guard = self.lock.lock();
|
||||
|
||||
// These two accesses are safe because we're guranteed at this point
|
||||
// that we have exclusive access to this mutex. We are indeed able to
|
||||
// promote ourselves from &Mutex to `&mut T`
|
||||
let poison = unsafe { &mut *self.failed.get() };
|
||||
let data = unsafe { &mut *self.data.get() };
|
||||
|
||||
MutexGuard {
|
||||
data: data,
|
||||
cond: Condvar {
|
||||
name: "Mutex",
|
||||
poison: PoisonOnFail::new(poison, "Mutex"),
|
||||
inner: InnerMutex(guard),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME(#13042): these should both have T: Send
|
||||
impl<'a, T> Deref<T> for MutexGuard<'a, T> {
|
||||
fn deref<'a>(&'a self) -> &'a T { &*self.data }
|
||||
}
|
||||
impl<'a, T> DerefMut<T> for MutexGuard<'a, T> {
|
||||
fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut *self.data }
|
||||
}
|
||||
|
||||
/****************************************************************************
|
||||
* R/W lock protected lock
|
||||
****************************************************************************/
|
||||
|
||||
/// A dual-mode reader-writer lock. The data can be accessed mutably or
|
||||
/// immutably, and immutably-accessing tasks may run concurrently.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use sync::{RWLock, Arc};
|
||||
///
|
||||
/// let lock1 = Arc::new(RWLock::new(1));
|
||||
/// let lock2 = lock1.clone();
|
||||
///
|
||||
/// spawn(proc() {
|
||||
/// let mut val = lock2.write();
|
||||
/// *val = 3;
|
||||
/// let val = val.downgrade();
|
||||
/// println!("{}", *val);
|
||||
/// });
|
||||
///
|
||||
/// let val = lock1.read();
|
||||
/// println!("{}", *val);
|
||||
/// ```
|
||||
pub struct RWLock<T> {
|
||||
priv lock: raw::RWLock,
|
||||
priv failed: Unsafe<bool>,
|
||||
priv data: Unsafe<T>,
|
||||
}
|
||||
|
||||
/// A guard which is created by locking an rwlock in write mode. Through this
|
||||
/// guard the underlying data can be accessed.
|
||||
pub struct RWLockWriteGuard<'a, T> {
|
||||
priv data: &'a mut T,
|
||||
/// Inner condition variable that can be used to sleep on the write mode of
|
||||
/// this rwlock.
|
||||
cond: Condvar<'a>,
|
||||
}
|
||||
|
||||
/// A guard which is created by locking an rwlock in read mode. Through this
|
||||
/// guard the underlying data can be accessed.
|
||||
pub struct RWLockReadGuard<'a, T> {
|
||||
priv data: &'a T,
|
||||
priv guard: raw::RWLockReadGuard<'a>,
|
||||
}
|
||||
|
||||
impl<T: Send + Share> RWLock<T> {
|
||||
/// Create a reader/writer lock with the supplied data.
|
||||
pub fn new(user_data: T) -> RWLock<T> {
|
||||
RWLock::new_with_condvars(user_data, 1)
|
||||
}
|
||||
|
||||
/// Create a reader/writer lock with the supplied data and a specified number
|
||||
/// of condvars (as sync::RWLock::new_with_condvars).
|
||||
pub fn new_with_condvars(user_data: T, num_condvars: uint) -> RWLock<T> {
|
||||
RWLock {
|
||||
lock: raw::RWLock::new_with_condvars(num_condvars),
|
||||
failed: Unsafe::new(false),
|
||||
data: Unsafe::new(user_data),
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the underlying data mutably. Locks the rwlock in write mode;
|
||||
/// other readers and writers will block.
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
/// Failing while inside the lock will unlock the lock while unwinding, so
|
||||
/// that other tasks won't block forever. As Mutex.lock, it will also poison
|
||||
/// the lock, so subsequent readers and writers will both also fail.
|
||||
#[inline]
|
||||
pub fn write<'a>(&'a self) -> RWLockWriteGuard<'a, T> {
|
||||
let guard = self.lock.write();
|
||||
|
||||
// These two accesses are safe because we're guranteed at this point
|
||||
// that we have exclusive access to this rwlock. We are indeed able to
|
||||
// promote ourselves from &RWLock to `&mut T`
|
||||
let poison = unsafe { &mut *self.failed.get() };
|
||||
let data = unsafe { &mut *self.data.get() };
|
||||
|
||||
RWLockWriteGuard {
|
||||
data: data,
|
||||
cond: Condvar {
|
||||
name: "RWLock",
|
||||
poison: PoisonOnFail::new(poison, "RWLock"),
|
||||
inner: InnerRWLock(guard),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Access the underlying data immutably. May run concurrently with other
|
||||
/// reading tasks.
|
||||
///
|
||||
/// # Failure
|
||||
///
|
||||
/// Failing will unlock the lock while unwinding. However, unlike all other
|
||||
/// access modes, this will not poison the lock.
|
||||
pub fn read<'a>(&'a self) -> RWLockReadGuard<'a, T> {
|
||||
let guard = self.lock.read();
|
||||
PoisonOnFail::check(unsafe { *self.failed.get() }, "RWLock");
|
||||
RWLockReadGuard {
|
||||
guard: guard,
|
||||
data: unsafe { &*self.data.get() },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Send + Share> RWLockWriteGuard<'a, T> {
|
||||
/// Consumes this write lock token, returning a new read lock token.
|
||||
///
|
||||
/// This will allow pending readers to come into the lock.
|
||||
pub fn downgrade(self) -> RWLockReadGuard<'a, T> {
|
||||
let RWLockWriteGuard { data, cond } = self;
|
||||
// convert the data to read-only explicitly
|
||||
let data = &*data;
|
||||
let guard = match cond.inner {
|
||||
InnerMutex(..) => unreachable!(),
|
||||
InnerRWLock(guard) => guard.downgrade()
|
||||
};
|
||||
RWLockReadGuard { guard: guard, data: data }
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME(#13042): these should all have T: Send + Share
|
||||
impl<'a, T> Deref<T> for RWLockReadGuard<'a, T> {
|
||||
fn deref<'a>(&'a self) -> &'a T { self.data }
|
||||
}
|
||||
impl<'a, T> Deref<T> for RWLockWriteGuard<'a, T> {
|
||||
fn deref<'a>(&'a self) -> &'a T { &*self.data }
|
||||
}
|
||||
impl<'a, T> DerefMut<T> for RWLockWriteGuard<'a, T> {
|
||||
fn deref_mut<'a>(&'a mut self) -> &'a mut T { &mut *self.data }
|
||||
}
|
||||
|
||||
/****************************************************************************
|
||||
* Barrier
|
||||
****************************************************************************/
|
||||
|
||||
/// A barrier enables multiple tasks to synchronize the beginning
|
||||
/// of some computation.
|
||||
///
|
||||
/// ```rust
|
||||
/// use sync::{Arc, Barrier};
|
||||
///
|
||||
/// let barrier = Arc::new(Barrier::new(10));
|
||||
/// for _ in range(0, 10) {
|
||||
/// let c = barrier.clone();
|
||||
/// // The same messages will be printed together.
|
||||
/// // You will NOT see any interleaving.
|
||||
/// spawn(proc() {
|
||||
/// println!("before wait");
|
||||
/// c.wait();
|
||||
/// println!("after wait");
|
||||
/// });
|
||||
/// }
|
||||
/// ```
|
||||
pub struct Barrier {
|
||||
priv lock: Mutex<BarrierState>,
|
||||
priv num_tasks: uint,
|
||||
}
|
||||
|
||||
// The inner state of a double barrier
|
||||
struct BarrierState {
|
||||
count: uint,
|
||||
generation_id: uint,
|
||||
}
|
||||
|
||||
impl Barrier {
|
||||
/// Create a new barrier that can block a given number of tasks.
|
||||
pub fn new(num_tasks: uint) -> Barrier {
|
||||
Barrier {
|
||||
lock: Mutex::new(BarrierState {
|
||||
count: 0,
|
||||
generation_id: 0,
|
||||
}),
|
||||
num_tasks: num_tasks,
|
||||
}
|
||||
}
|
||||
|
||||
/// Block the current task until a certain number of tasks is waiting.
|
||||
pub fn wait(&self) {
|
||||
let mut lock = self.lock.lock();
|
||||
let local_gen = lock.generation_id;
|
||||
lock.count += 1;
|
||||
if lock.count < self.num_tasks {
|
||||
// We need a while loop to guard against spurious wakeups.
|
||||
// http://en.wikipedia.org/wiki/Spurious_wakeup
|
||||
while local_gen == lock.generation_id &&
|
||||
lock.count < self.num_tasks {
|
||||
lock.cond.wait();
|
||||
}
|
||||
} else {
|
||||
lock.count = 0;
|
||||
lock.generation_id += 1;
|
||||
lock.cond.broadcast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/****************************************************************************
|
||||
* Tests
|
||||
****************************************************************************/
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::comm::Empty;
|
||||
use std::task;
|
||||
|
||||
use arc::Arc;
|
||||
use super::{Mutex, Barrier, RWLock};
|
||||
|
||||
#[test]
|
||||
fn test_mutex_arc_condvar() {
|
||||
let arc = Arc::new(Mutex::new(false));
|
||||
let arc2 = arc.clone();
|
||||
let (tx, rx) = channel();
|
||||
task::spawn(proc() {
|
||||
// wait until parent gets in
|
||||
rx.recv();
|
||||
let mut lock = arc2.lock();
|
||||
*lock = true;
|
||||
lock.cond.signal();
|
||||
});
|
||||
|
||||
let lock = arc.lock();
|
||||
tx.send(());
|
||||
assert!(!*lock);
|
||||
while !*lock {
|
||||
lock.cond.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test] #[should_fail]
|
||||
fn test_arc_condvar_poison() {
|
||||
let arc = Arc::new(Mutex::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let (tx, rx) = channel();
|
||||
|
||||
spawn(proc() {
|
||||
rx.recv();
|
||||
let lock = arc2.lock();
|
||||
lock.cond.signal();
|
||||
// Parent should fail when it wakes up.
|
||||
fail!();
|
||||
});
|
||||
|
||||
let lock = arc.lock();
|
||||
tx.send(());
|
||||
while *lock == 1 {
|
||||
lock.cond.wait();
|
||||
}
|
||||
}
|
||||
|
||||
#[test] #[should_fail]
|
||||
fn test_mutex_arc_poison() {
|
||||
let arc = Arc::new(Mutex::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try(proc() {
|
||||
let lock = arc2.lock();
|
||||
assert_eq!(*lock, 2);
|
||||
});
|
||||
let lock = arc.lock();
|
||||
assert_eq!(*lock, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mutex_arc_nested() {
|
||||
// Tests nested mutexes and access
|
||||
// to underlaying data.
|
||||
let arc = Arc::new(Mutex::new(1));
|
||||
let arc2 = Arc::new(Mutex::new(arc));
|
||||
task::spawn(proc() {
|
||||
let lock = arc2.lock();
|
||||
let lock2 = lock.deref().lock();
|
||||
assert_eq!(*lock2, 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_mutex_arc_access_in_unwind() {
|
||||
let arc = Arc::new(Mutex::new(1i));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try::<()>(proc() {
|
||||
struct Unwinder {
|
||||
i: Arc<Mutex<int>>,
|
||||
}
|
||||
impl Drop for Unwinder {
|
||||
fn drop(&mut self) {
|
||||
let mut lock = self.i.lock();
|
||||
*lock += 1;
|
||||
}
|
||||
}
|
||||
let _u = Unwinder { i: arc2 };
|
||||
fail!();
|
||||
});
|
||||
let lock = arc.lock();
|
||||
assert_eq!(*lock, 2);
|
||||
}
|
||||
|
||||
#[test] #[should_fail]
|
||||
fn test_rw_arc_poison_wr() {
|
||||
let arc = Arc::new(RWLock::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try(proc() {
|
||||
let lock = arc2.write();
|
||||
assert_eq!(*lock, 2);
|
||||
});
|
||||
let lock = arc.read();
|
||||
assert_eq!(*lock, 1);
|
||||
}
|
||||
#[test] #[should_fail]
|
||||
fn test_rw_arc_poison_ww() {
|
||||
let arc = Arc::new(RWLock::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try(proc() {
|
||||
let lock = arc2.write();
|
||||
assert_eq!(*lock, 2);
|
||||
});
|
||||
let lock = arc.write();
|
||||
assert_eq!(*lock, 1);
|
||||
}
|
||||
#[test]
|
||||
fn test_rw_arc_no_poison_rr() {
|
||||
let arc = Arc::new(RWLock::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try(proc() {
|
||||
let lock = arc2.read();
|
||||
assert_eq!(*lock, 2);
|
||||
});
|
||||
let lock = arc.read();
|
||||
assert_eq!(*lock, 1);
|
||||
}
|
||||
#[test]
|
||||
fn test_rw_arc_no_poison_rw() {
|
||||
let arc = Arc::new(RWLock::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try(proc() {
|
||||
let lock = arc2.read();
|
||||
assert_eq!(*lock, 2);
|
||||
});
|
||||
let lock = arc.write();
|
||||
assert_eq!(*lock, 1);
|
||||
}
|
||||
#[test]
|
||||
fn test_rw_arc_no_poison_dr() {
|
||||
let arc = Arc::new(RWLock::new(1));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try(proc() {
|
||||
let lock = arc2.write().downgrade();
|
||||
assert_eq!(*lock, 2);
|
||||
});
|
||||
let lock = arc.write();
|
||||
assert_eq!(*lock, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rw_arc() {
|
||||
let arc = Arc::new(RWLock::new(0));
|
||||
let arc2 = arc.clone();
|
||||
let (tx, rx) = channel();
|
||||
|
||||
task::spawn(proc() {
|
||||
let mut lock = arc2.write();
|
||||
for _ in range(0, 10) {
|
||||
let tmp = *lock;
|
||||
*lock = -1;
|
||||
task::deschedule();
|
||||
*lock = tmp + 1;
|
||||
}
|
||||
tx.send(());
|
||||
});
|
||||
|
||||
// Readers try to catch the writer in the act
|
||||
let mut children = Vec::new();
|
||||
for _ in range(0, 5) {
|
||||
let arc3 = arc.clone();
|
||||
let mut builder = task::task();
|
||||
children.push(builder.future_result());
|
||||
builder.spawn(proc() {
|
||||
let lock = arc3.read();
|
||||
assert!(*lock >= 0);
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for children to pass their asserts
|
||||
for r in children.mut_iter() {
|
||||
assert!(r.recv().is_ok());
|
||||
}
|
||||
|
||||
// Wait for writer to finish
|
||||
rx.recv();
|
||||
let lock = arc.read();
|
||||
assert_eq!(*lock, 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rw_arc_access_in_unwind() {
|
||||
let arc = Arc::new(RWLock::new(1i));
|
||||
let arc2 = arc.clone();
|
||||
let _ = task::try::<()>(proc() {
|
||||
struct Unwinder {
|
||||
i: Arc<RWLock<int>>,
|
||||
}
|
||||
impl Drop for Unwinder {
|
||||
fn drop(&mut self) {
|
||||
let mut lock = self.i.write();
|
||||
*lock += 1;
|
||||
}
|
||||
}
|
||||
let _u = Unwinder { i: arc2 };
|
||||
fail!();
|
||||
});
|
||||
let lock = arc.read();
|
||||
assert_eq!(*lock, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rw_downgrade() {
|
||||
// (1) A downgrader gets in write mode and does cond.wait.
|
||||
// (2) A writer gets in write mode, sets state to 42, and does signal.
|
||||
// (3) Downgrader wakes, sets state to 31337.
|
||||
// (4) tells writer and all other readers to contend as it downgrades.
|
||||
// (5) Writer attempts to set state back to 42, while downgraded task
|
||||
// and all reader tasks assert that it's 31337.
|
||||
let arc = Arc::new(RWLock::new(0));
|
||||
|
||||
// Reader tasks
|
||||
let mut reader_convos = Vec::new();
|
||||
for _ in range(0, 10) {
|
||||
let ((tx1, rx1), (tx2, rx2)) = (channel(), channel());
|
||||
reader_convos.push((tx1, rx2));
|
||||
let arcn = arc.clone();
|
||||
task::spawn(proc() {
|
||||
rx1.recv(); // wait for downgrader to give go-ahead
|
||||
let lock = arcn.read();
|
||||
assert_eq!(*lock, 31337);
|
||||
tx2.send(());
|
||||
});
|
||||
}
|
||||
|
||||
// Writer task
|
||||
let arc2 = arc.clone();
|
||||
let ((tx1, rx1), (tx2, rx2)) = (channel(), channel());
|
||||
task::spawn(proc() {
|
||||
rx1.recv();
|
||||
{
|
||||
let mut lock = arc2.write();
|
||||
assert_eq!(*lock, 0);
|
||||
*lock = 42;
|
||||
lock.cond.signal();
|
||||
}
|
||||
rx1.recv();
|
||||
{
|
||||
let mut lock = arc2.write();
|
||||
// This shouldn't happen until after the downgrade read
|
||||
// section, and all other readers, finish.
|
||||
assert_eq!(*lock, 31337);
|
||||
*lock = 42;
|
||||
}
|
||||
tx2.send(());
|
||||
});
|
||||
|
||||
// Downgrader (us)
|
||||
let mut lock = arc.write();
|
||||
tx1.send(()); // send to another writer who will wake us up
|
||||
while *lock == 0 {
|
||||
lock.cond.wait();
|
||||
}
|
||||
assert_eq!(*lock, 42);
|
||||
*lock = 31337;
|
||||
// send to other readers
|
||||
for &(ref mut rc, _) in reader_convos.mut_iter() {
|
||||
rc.send(())
|
||||
}
|
||||
let lock = lock.downgrade();
|
||||
// complete handshake with other readers
|
||||
for &(_, ref mut rp) in reader_convos.mut_iter() {
|
||||
rp.recv()
|
||||
}
|
||||
tx1.send(()); // tell writer to try again
|
||||
assert_eq!(*lock, 31337);
|
||||
drop(lock);
|
||||
|
||||
rx2.recv(); // complete handshake with writer
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn test_rw_write_cond_downgrade_read_race_helper() {
|
||||
// Tests that when a downgrader hands off the "reader cloud" lock
|
||||
// because of a contending reader, a writer can't race to get it
|
||||
// instead, which would result in readers_and_writers. This tests
|
||||
// the raw module rather than this one, but it's here because an
|
||||
// rwarc gives us extra shared state to help check for the race.
|
||||
let x = Arc::new(RWLock::new(true));
|
||||
let (tx, rx) = channel();
|
||||
|
||||
// writer task
|
||||
let xw = x.clone();
|
||||
task::spawn(proc() {
|
||||
let mut lock = xw.write();
|
||||
tx.send(()); // tell downgrader it's ok to go
|
||||
lock.cond.wait();
|
||||
// The core of the test is here: the condvar reacquire path
|
||||
// must involve order_lock, so that it cannot race with a reader
|
||||
// trying to receive the "reader cloud lock hand-off".
|
||||
*lock = false;
|
||||
});
|
||||
|
||||
rx.recv(); // wait for writer to get in
|
||||
|
||||
let lock = x.write();
|
||||
assert!(*lock);
|
||||
// make writer contend in the cond-reacquire path
|
||||
lock.cond.signal();
|
||||
// make a reader task to trigger the "reader cloud lock" handoff
|
||||
let xr = x.clone();
|
||||
let (tx, rx) = channel();
|
||||
task::spawn(proc() {
|
||||
tx.send(());
|
||||
drop(xr.read());
|
||||
});
|
||||
rx.recv(); // wait for reader task to exist
|
||||
|
||||
let lock = lock.downgrade();
|
||||
// if writer mistakenly got in, make sure it mutates state
|
||||
// before we assert on it
|
||||
for _ in range(0, 5) { task::deschedule(); }
|
||||
// make sure writer didn't get in.
|
||||
assert!(*lock);
|
||||
}
|
||||
#[test]
|
||||
fn test_rw_write_cond_downgrade_read_race() {
|
||||
// Ideally the above test case would have deschedule statements in it
|
||||
// that helped to expose the race nearly 100% of the time... but adding
|
||||
// deschedules in the intuitively-right locations made it even less
|
||||
// likely, and I wasn't sure why :( . This is a mediocre "next best"
|
||||
// option.
|
||||
for _ in range(0, 8) {
|
||||
test_rw_write_cond_downgrade_read_race_helper();
|
||||
}
|
||||
}
|
||||
|
||||
/************************************************************************
|
||||
* Barrier tests
|
||||
************************************************************************/
|
||||
#[test]
|
||||
fn test_barrier() {
|
||||
let barrier = Arc::new(Barrier::new(10));
|
||||
let (tx, rx) = channel();
|
||||
|
||||
for _ in range(0, 9) {
|
||||
let c = barrier.clone();
|
||||
let tx = tx.clone();
|
||||
spawn(proc() {
|
||||
c.wait();
|
||||
tx.send(true);
|
||||
});
|
||||
}
|
||||
|
||||
// At this point, all spawned tasks should be blocked,
|
||||
// so we shouldn't get anything from the port
|
||||
assert!(match rx.try_recv() {
|
||||
Empty => true,
|
||||
_ => false,
|
||||
});
|
||||
|
||||
barrier.wait();
|
||||
// Now, the barrier is cleared and we should get data.
|
||||
for _ in range(0, 9) {
|
||||
rx.recv();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -35,6 +35,7 @@
|
|||
|
||||
use std::cast;
|
||||
use std::sync::atomics;
|
||||
use std::ty::Unsafe;
|
||||
|
||||
// NB: all links are done as AtomicUint instead of AtomicPtr to allow for static
|
||||
// initialization.
|
||||
|
@ -50,7 +51,7 @@ pub struct DummyNode {
|
|||
|
||||
pub struct Queue<T> {
|
||||
head: atomics::AtomicUint,
|
||||
tail: *mut Node<T>,
|
||||
tail: Unsafe<*mut Node<T>>,
|
||||
stub: DummyNode,
|
||||
}
|
||||
|
||||
|
@ -58,14 +59,14 @@ impl<T: Send> Queue<T> {
|
|||
pub fn new() -> Queue<T> {
|
||||
Queue {
|
||||
head: atomics::AtomicUint::new(0),
|
||||
tail: 0 as *mut Node<T>,
|
||||
tail: Unsafe::new(0 as *mut Node<T>),
|
||||
stub: DummyNode {
|
||||
next: atomics::AtomicUint::new(0),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn push(&mut self, node: *mut Node<T>) {
|
||||
pub unsafe fn push(&self, node: *mut Node<T>) {
|
||||
(*node).next.store(0, atomics::Release);
|
||||
let prev = self.head.swap(node as uint, atomics::AcqRel);
|
||||
|
||||
|
@ -93,8 +94,8 @@ impl<T: Send> Queue<T> {
|
|||
/// Right now consumers of this queue must be ready for this fact. Just
|
||||
/// because `pop` returns `None` does not mean that there is not data
|
||||
/// on the queue.
|
||||
pub unsafe fn pop(&mut self) -> Option<*mut Node<T>> {
|
||||
let tail = self.tail;
|
||||
pub unsafe fn pop(&self) -> Option<*mut Node<T>> {
|
||||
let tail = *self.tail.get();
|
||||
let mut tail = if !tail.is_null() {tail} else {
|
||||
cast::transmute(&self.stub)
|
||||
};
|
||||
|
@ -103,12 +104,12 @@ impl<T: Send> Queue<T> {
|
|||
if next.is_null() {
|
||||
return None;
|
||||
}
|
||||
self.tail = next;
|
||||
*self.tail.get() = next;
|
||||
tail = next;
|
||||
next = (*next).next(atomics::Relaxed);
|
||||
}
|
||||
if !next.is_null() {
|
||||
self.tail = next;
|
||||
*self.tail.get() = next;
|
||||
return Some(tail);
|
||||
}
|
||||
let head = self.head.load(atomics::Acquire) as *mut Node<T>;
|
||||
|
@ -119,7 +120,7 @@ impl<T: Send> Queue<T> {
|
|||
self.push(stub);
|
||||
next = (*tail).next(atomics::Relaxed);
|
||||
if !next.is_null() {
|
||||
self.tail = next;
|
||||
*self.tail.get() = next;
|
||||
return Some(tail);
|
||||
}
|
||||
return None
|
||||
|
@ -133,7 +134,7 @@ impl<T: Send> Node<T> {
|
|||
next: atomics::AtomicUint::new(0),
|
||||
}
|
||||
}
|
||||
pub unsafe fn next(&mut self, ord: atomics::Ordering) -> *mut Node<T> {
|
||||
pub unsafe fn next(&self, ord: atomics::Ordering) -> *mut Node<T> {
|
||||
cast::transmute::<uint, *mut Node<T>>(self.next.load(ord))
|
||||
}
|
||||
}
|
|
@ -57,13 +57,16 @@
|
|||
// times in order to manage a few flags about who's blocking where and whether
|
||||
// it's locked or not.
|
||||
|
||||
use std::kinds::marker;
|
||||
use std::mem;
|
||||
use std::rt::local::Local;
|
||||
use std::rt::task::{BlockedTask, Task};
|
||||
use std::rt::thread::Thread;
|
||||
use std::sync::atomics;
|
||||
use std::ty::Unsafe;
|
||||
use std::unstable::mutex;
|
||||
|
||||
use q = sync::mpsc_intrusive;
|
||||
use q = mpsc_intrusive;
|
||||
|
||||
pub static LOCKED: uint = 1 << 0;
|
||||
pub static GREEN_BLOCKED: uint = 1 << 1;
|
||||
|
@ -85,7 +88,7 @@ pub static NATIVE_BLOCKED: uint = 1 << 2;
|
|||
/// ```rust
|
||||
/// use sync::mutex::Mutex;
|
||||
///
|
||||
/// let mut m = Mutex::new();
|
||||
/// let m = Mutex::new();
|
||||
/// let guard = m.lock();
|
||||
/// // do some work
|
||||
/// drop(guard); // unlock the lock
|
||||
|
@ -126,15 +129,16 @@ enum Flavor {
|
|||
pub struct StaticMutex {
|
||||
/// Current set of flags on this mutex
|
||||
priv state: atomics::AtomicUint,
|
||||
/// Type of locking operation currently on this mutex
|
||||
priv flavor: Flavor,
|
||||
/// uint-cast of the green thread waiting for this mutex
|
||||
priv green_blocker: uint,
|
||||
/// uint-cast of the native thread waiting for this mutex
|
||||
priv native_blocker: uint,
|
||||
/// an OS mutex used by native threads
|
||||
priv lock: mutex::StaticNativeMutex,
|
||||
|
||||
/// Type of locking operation currently on this mutex
|
||||
priv flavor: Unsafe<Flavor>,
|
||||
/// uint-cast of the green thread waiting for this mutex
|
||||
priv green_blocker: Unsafe<uint>,
|
||||
/// uint-cast of the native thread waiting for this mutex
|
||||
priv native_blocker: Unsafe<uint>,
|
||||
|
||||
/// A concurrent mpsc queue used by green threads, along with a count used
|
||||
/// to figure out when to dequeue and enqueue.
|
||||
priv q: q::Queue<uint>,
|
||||
|
@ -145,7 +149,7 @@ pub struct StaticMutex {
|
|||
/// dropped (falls out of scope), the lock will be unlocked.
|
||||
#[must_use]
|
||||
pub struct Guard<'a> {
|
||||
priv lock: &'a mut StaticMutex,
|
||||
priv lock: &'a StaticMutex,
|
||||
}
|
||||
|
||||
/// Static initialization of a mutex. This constant can be used to initialize
|
||||
|
@ -153,13 +157,16 @@ pub struct Guard<'a> {
|
|||
pub static MUTEX_INIT: StaticMutex = StaticMutex {
|
||||
lock: mutex::NATIVE_MUTEX_INIT,
|
||||
state: atomics::INIT_ATOMIC_UINT,
|
||||
flavor: Unlocked,
|
||||
green_blocker: 0,
|
||||
native_blocker: 0,
|
||||
flavor: Unsafe { value: Unlocked, marker1: marker::InvariantType },
|
||||
green_blocker: Unsafe { value: 0, marker1: marker::InvariantType },
|
||||
native_blocker: Unsafe { value: 0, marker1: marker::InvariantType },
|
||||
green_cnt: atomics::INIT_ATOMIC_UINT,
|
||||
q: q::Queue {
|
||||
head: atomics::INIT_ATOMIC_UINT,
|
||||
tail: 0 as *mut q::Node<uint>,
|
||||
tail: Unsafe {
|
||||
value: 0 as *mut q::Node<uint>,
|
||||
marker1: marker::InvariantType,
|
||||
},
|
||||
stub: q::DummyNode {
|
||||
next: atomics::INIT_ATOMIC_UINT,
|
||||
}
|
||||
|
@ -168,14 +175,18 @@ pub static MUTEX_INIT: StaticMutex = StaticMutex {
|
|||
|
||||
impl StaticMutex {
|
||||
/// Attempts to grab this lock, see `Mutex::try_lock`
|
||||
pub fn try_lock<'a>(&'a mut self) -> Option<Guard<'a>> {
|
||||
pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
|
||||
// Attempt to steal the mutex from an unlocked state.
|
||||
//
|
||||
// FIXME: this can mess up the fairness of the mutex, seems bad
|
||||
match self.state.compare_and_swap(0, LOCKED, atomics::SeqCst) {
|
||||
0 => {
|
||||
assert!(self.flavor == Unlocked);
|
||||
self.flavor = TryLockAcquisition;
|
||||
// After acquiring the mutex, we can safely access the inner
|
||||
// fields.
|
||||
let prev = unsafe {
|
||||
mem::replace(&mut *self.flavor.get(), TryLockAcquisition)
|
||||
};
|
||||
assert_eq!(prev, Unlocked);
|
||||
Some(Guard::new(self))
|
||||
}
|
||||
_ => None
|
||||
|
@ -183,19 +194,15 @@ impl StaticMutex {
|
|||
}
|
||||
|
||||
/// Acquires this lock, see `Mutex::lock`
|
||||
pub fn lock<'a>(&'a mut self) -> Guard<'a> {
|
||||
pub fn lock<'a>(&'a self) -> Guard<'a> {
|
||||
// First, attempt to steal the mutex from an unlocked state. The "fast
|
||||
// path" needs to have as few atomic instructions as possible, and this
|
||||
// one cmpxchg is already pretty expensive.
|
||||
//
|
||||
// FIXME: this can mess up the fairness of the mutex, seems bad
|
||||
match self.state.compare_and_swap(0, LOCKED, atomics::SeqCst) {
|
||||
0 => {
|
||||
assert!(self.flavor == Unlocked);
|
||||
self.flavor = TryLockAcquisition;
|
||||
return Guard::new(self)
|
||||
}
|
||||
_ => {}
|
||||
match self.try_lock() {
|
||||
Some(guard) => return guard,
|
||||
None => {}
|
||||
}
|
||||
|
||||
// After we've failed the fast path, then we delegate to the differnet
|
||||
|
@ -219,11 +226,14 @@ impl StaticMutex {
|
|||
let mut old = match self.state.compare_and_swap(0, LOCKED,
|
||||
atomics::SeqCst) {
|
||||
0 => {
|
||||
self.flavor = if can_block {
|
||||
let flavor = if can_block {
|
||||
NativeAcquisition
|
||||
} else {
|
||||
GreenAcquisition
|
||||
};
|
||||
// We've acquired the lock, so this unsafe access to flavor is
|
||||
// allowed.
|
||||
unsafe { *self.flavor.get() = flavor; }
|
||||
return Guard::new(self)
|
||||
}
|
||||
old => old,
|
||||
|
@ -237,13 +247,15 @@ impl StaticMutex {
|
|||
let t: ~Task = Local::take();
|
||||
t.deschedule(1, |task| {
|
||||
let task = unsafe { task.cast_to_uint() };
|
||||
if can_block {
|
||||
assert_eq!(self.native_blocker, 0);
|
||||
self.native_blocker = task;
|
||||
|
||||
// These accesses are protected by the respective native/green
|
||||
// mutexes which were acquired above.
|
||||
let prev = if can_block {
|
||||
unsafe { mem::replace(&mut *self.native_blocker.get(), task) }
|
||||
} else {
|
||||
assert_eq!(self.green_blocker, 0);
|
||||
self.green_blocker = task;
|
||||
}
|
||||
unsafe { mem::replace(&mut *self.green_blocker.get(), task) }
|
||||
};
|
||||
assert_eq!(prev, 0);
|
||||
|
||||
loop {
|
||||
assert_eq!(old & native_bit, 0);
|
||||
|
@ -264,14 +276,23 @@ impl StaticMutex {
|
|||
old | LOCKED,
|
||||
atomics::SeqCst) {
|
||||
n if n == old => {
|
||||
assert_eq!(self.flavor, Unlocked);
|
||||
if can_block {
|
||||
self.native_blocker = 0;
|
||||
self.flavor = NativeAcquisition;
|
||||
// After acquiring the lock, we have access to the
|
||||
// flavor field, and we've regained access to our
|
||||
// respective native/green blocker field.
|
||||
let prev = if can_block {
|
||||
unsafe {
|
||||
*self.native_blocker.get() = 0;
|
||||
mem::replace(&mut *self.flavor.get(),
|
||||
NativeAcquisition)
|
||||
}
|
||||
} else {
|
||||
self.green_blocker = 0;
|
||||
self.flavor = GreenAcquisition;
|
||||
}
|
||||
unsafe {
|
||||
*self.green_blocker.get() = 0;
|
||||
mem::replace(&mut *self.flavor.get(),
|
||||
GreenAcquisition)
|
||||
}
|
||||
};
|
||||
assert_eq!(prev, Unlocked);
|
||||
return Err(unsafe {
|
||||
BlockedTask::cast_from_uint(task)
|
||||
})
|
||||
|
@ -287,16 +308,16 @@ impl StaticMutex {
|
|||
|
||||
// Tasks which can block are super easy. These tasks just call the blocking
|
||||
// `lock()` function on an OS mutex
|
||||
fn native_lock(&mut self, t: ~Task) {
|
||||
fn native_lock(&self, t: ~Task) {
|
||||
Local::put(t);
|
||||
unsafe { self.lock.lock_noguard(); }
|
||||
}
|
||||
|
||||
fn native_unlock(&mut self) {
|
||||
fn native_unlock(&self) {
|
||||
unsafe { self.lock.unlock_noguard(); }
|
||||
}
|
||||
|
||||
fn green_lock(&mut self, t: ~Task) {
|
||||
fn green_lock(&self, t: ~Task) {
|
||||
// Green threads flag their presence with an atomic counter, and if they
|
||||
// fail to be the first to the mutex, they enqueue themselves on a
|
||||
// concurrent internal queue with a stack-allocated node.
|
||||
|
@ -318,7 +339,7 @@ impl StaticMutex {
|
|||
});
|
||||
}
|
||||
|
||||
fn green_unlock(&mut self) {
|
||||
fn green_unlock(&self) {
|
||||
// If we're the only green thread, then no need to check the queue,
|
||||
// otherwise the fixme above forces us to spin for a bit.
|
||||
if self.green_cnt.fetch_sub(1, atomics::SeqCst) == 1 { return }
|
||||
|
@ -333,7 +354,7 @@ impl StaticMutex {
|
|||
task.wake().map(|t| t.reawaken());
|
||||
}
|
||||
|
||||
fn unlock(&mut self) {
|
||||
fn unlock(&self) {
|
||||
// Unlocking this mutex is a little tricky. We favor any task that is
|
||||
// manually blocked (not in each of the separate locks) in order to help
|
||||
// provide a little fairness (green threads will wake up the pending
|
||||
|
@ -351,8 +372,7 @@ impl StaticMutex {
|
|||
// task needs to be woken, and in this case it's ok that the "mutex
|
||||
// halves" are unlocked, we're just mainly dealing with the atomic state
|
||||
// of the outer mutex.
|
||||
let flavor = self.flavor;
|
||||
self.flavor = Unlocked;
|
||||
let flavor = unsafe { mem::replace(&mut *self.flavor.get(), Unlocked) };
|
||||
|
||||
let mut state = self.state.load(atomics::SeqCst);
|
||||
let mut unlocked = false;
|
||||
|
@ -362,18 +382,18 @@ impl StaticMutex {
|
|||
if state & GREEN_BLOCKED != 0 {
|
||||
self.unset(state, GREEN_BLOCKED);
|
||||
task = unsafe {
|
||||
BlockedTask::cast_from_uint(self.green_blocker)
|
||||
*self.flavor.get() = GreenAcquisition;
|
||||
let task = mem::replace(&mut *self.green_blocker.get(), 0);
|
||||
BlockedTask::cast_from_uint(task)
|
||||
};
|
||||
self.green_blocker = 0;
|
||||
self.flavor = GreenAcquisition;
|
||||
break;
|
||||
} else if state & NATIVE_BLOCKED != 0 {
|
||||
self.unset(state, NATIVE_BLOCKED);
|
||||
task = unsafe {
|
||||
BlockedTask::cast_from_uint(self.native_blocker)
|
||||
*self.flavor.get() = NativeAcquisition;
|
||||
let task = mem::replace(&mut *self.native_blocker.get(), 0);
|
||||
BlockedTask::cast_from_uint(task)
|
||||
};
|
||||
self.native_blocker = 0;
|
||||
self.flavor = NativeAcquisition;
|
||||
break;
|
||||
} else {
|
||||
assert_eq!(state, LOCKED);
|
||||
|
@ -405,7 +425,7 @@ impl StaticMutex {
|
|||
}
|
||||
|
||||
/// Loops around a CAS to unset the `bit` in `state`
|
||||
fn unset(&mut self, mut state: uint, bit: uint) {
|
||||
fn unset(&self, mut state: uint, bit: uint) {
|
||||
loop {
|
||||
assert!(state & bit != 0);
|
||||
let new = state ^ bit;
|
||||
|
@ -426,7 +446,7 @@ impl StaticMutex {
|
|||
/// *all* platforms. It may be the case that some platforms do not leak
|
||||
/// memory if this method is not called, but this is not guaranteed to be
|
||||
/// true on all platforms.
|
||||
pub unsafe fn destroy(&mut self) {
|
||||
pub unsafe fn destroy(&self) {
|
||||
self.lock.destroy()
|
||||
}
|
||||
}
|
||||
|
@ -437,9 +457,9 @@ impl Mutex {
|
|||
Mutex {
|
||||
lock: StaticMutex {
|
||||
state: atomics::AtomicUint::new(0),
|
||||
flavor: Unlocked,
|
||||
green_blocker: 0,
|
||||
native_blocker: 0,
|
||||
flavor: Unsafe::new(Unlocked),
|
||||
green_blocker: Unsafe::new(0),
|
||||
native_blocker: Unsafe::new(0),
|
||||
green_cnt: atomics::AtomicUint::new(0),
|
||||
q: q::Queue::new(),
|
||||
lock: unsafe { mutex::StaticNativeMutex::new() },
|
||||
|
@ -454,7 +474,7 @@ impl Mutex {
|
|||
/// guard is dropped.
|
||||
///
|
||||
/// This function does not block.
|
||||
pub fn try_lock<'a>(&'a mut self) -> Option<Guard<'a>> {
|
||||
pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
|
||||
self.lock.try_lock()
|
||||
}
|
||||
|
||||
|
@ -464,13 +484,14 @@ impl Mutex {
|
|||
/// the mutex. Upon returning, the task is the only task with the mutex
|
||||
/// held. An RAII guard is returned to allow scoped unlock of the lock. When
|
||||
/// the guard goes out of scope, the mutex will be unlocked.
|
||||
pub fn lock<'a>(&'a mut self) -> Guard<'a> { self.lock.lock() }
|
||||
pub fn lock<'a>(&'a self) -> Guard<'a> { self.lock.lock() }
|
||||
}
|
||||
|
||||
impl<'a> Guard<'a> {
|
||||
fn new<'b>(lock: &'b mut StaticMutex) -> Guard<'b> {
|
||||
fn new<'b>(lock: &'b StaticMutex) -> Guard<'b> {
|
||||
if cfg!(debug) {
|
||||
assert!(lock.flavor != Unlocked);
|
||||
// once we've acquired a lock, it's ok to access the flavor
|
||||
assert!(unsafe { *lock.flavor.get() != Unlocked });
|
||||
assert!(lock.state.load(atomics::SeqCst) & LOCKED != 0);
|
||||
}
|
||||
Guard { lock: lock }
|
||||
|
@ -501,7 +522,7 @@ mod test {
|
|||
|
||||
#[test]
|
||||
fn smoke() {
|
||||
let mut m = Mutex::new();
|
||||
let m = Mutex::new();
|
||||
drop(m.lock());
|
||||
drop(m.lock());
|
||||
}
|
||||
|
@ -552,7 +573,7 @@ mod test {
|
|||
|
||||
#[test]
|
||||
fn trylock() {
|
||||
let mut m = Mutex::new();
|
||||
let m = Mutex::new();
|
||||
assert!(m.try_lock().is_some());
|
||||
}
|
||||
}
|
|
@ -15,7 +15,8 @@
|
|||
|
||||
use std::int;
|
||||
use std::sync::atomics;
|
||||
use sync::mutex::{StaticMutex, MUTEX_INIT};
|
||||
|
||||
use mutex::{StaticMutex, MUTEX_INIT};
|
||||
|
||||
/// A type which can be used to run a one-time global initialization. This type
|
||||
/// is *unsafe* to use because it is built on top of the `Mutex` in this module.
|
||||
|
@ -62,7 +63,7 @@ impl Once {
|
|||
///
|
||||
/// When this function returns, it is guaranteed that some initialization
|
||||
/// has run and completed (it may not be the closure specified).
|
||||
pub fn doit(&mut self, f: ||) {
|
||||
pub fn doit(&self, f: ||) {
|
||||
// Implementation-wise, this would seem like a fairly trivial primitive.
|
||||
// The stickler part is where our mutexes currently require an
|
||||
// allocation, and usage of a `Once` should't leak this allocation.
|
||||
|
@ -101,14 +102,13 @@ impl Once {
|
|||
// If the count is negative, then someone else finished the job,
|
||||
// otherwise we run the job and record how many people will try to grab
|
||||
// this lock
|
||||
{
|
||||
let _guard = self.mutex.lock();
|
||||
if self.cnt.load(atomics::SeqCst) > 0 {
|
||||
f();
|
||||
let prev = self.cnt.swap(int::MIN, atomics::SeqCst);
|
||||
self.lock_cnt.store(prev, atomics::SeqCst);
|
||||
}
|
||||
let guard = self.mutex.lock();
|
||||
if self.cnt.load(atomics::SeqCst) > 0 {
|
||||
f();
|
||||
let prev = self.cnt.swap(int::MIN, atomics::SeqCst);
|
||||
self.lock_cnt.store(prev, atomics::SeqCst);
|
||||
}
|
||||
drop(guard);
|
||||
|
||||
// Last one out cleans up after everyone else, no leaks!
|
||||
if self.lock_cnt.fetch_add(-1, atomics::SeqCst) == 1 {
|
File diff suppressed because it is too large
Load diff
|
@ -26,7 +26,7 @@ extern crate sync;
|
|||
use serialize::json;
|
||||
use serialize::json::ToJson;
|
||||
use serialize::{Encoder, Encodable, Decoder, Decodable};
|
||||
use sync::{Arc,RWArc};
|
||||
use sync::{Arc, RWLock};
|
||||
use collections::TreeMap;
|
||||
use std::str;
|
||||
use std::io;
|
||||
|
@ -225,7 +225,7 @@ pub type FreshnessMap = TreeMap<~str,extern fn(&str,&str)->bool>;
|
|||
|
||||
#[deriving(Clone)]
|
||||
pub struct Context {
|
||||
db: RWArc<Database>,
|
||||
db: Arc<RWLock<Database>>,
|
||||
priv cfg: Arc<json::Object>,
|
||||
/// Map from kinds (source, exe, url, etc.) to a freshness function.
|
||||
/// The freshness function takes a name (e.g. file path) and value
|
||||
|
@ -269,12 +269,12 @@ fn json_decode<T:Decodable<json::Decoder>>(s: &str) -> T {
|
|||
|
||||
impl Context {
|
||||
|
||||
pub fn new(db: RWArc<Database>,
|
||||
pub fn new(db: Arc<RWLock<Database>>,
|
||||
cfg: Arc<json::Object>) -> Context {
|
||||
Context::new_with_freshness(db, cfg, Arc::new(TreeMap::new()))
|
||||
}
|
||||
|
||||
pub fn new_with_freshness(db: RWArc<Database>,
|
||||
pub fn new_with_freshness(db: Arc<RWLock<Database>>,
|
||||
cfg: Arc<json::Object>,
|
||||
freshness: Arc<FreshnessMap>) -> Context {
|
||||
Context {
|
||||
|
@ -364,7 +364,7 @@ impl<'a> Prep<'a> {
|
|||
fn is_fresh(&self, cat: &str, kind: &str,
|
||||
name: &str, val: &str) -> bool {
|
||||
let k = kind.to_owned();
|
||||
let f = self.ctxt.freshness.get().find(&k);
|
||||
let f = self.ctxt.freshness.deref().find(&k);
|
||||
debug!("freshness for: {}/{}/{}/{}", cat, kind, name, val)
|
||||
let fresh = match f {
|
||||
None => fail!("missing freshness-function for '{}'", kind),
|
||||
|
@ -406,9 +406,10 @@ impl<'a> Prep<'a> {
|
|||
|
||||
debug!("exec_work: looking up {} and {:?}", self.fn_name,
|
||||
self.declared_inputs);
|
||||
let cached = self.ctxt.db.read(|db| {
|
||||
db.prepare(self.fn_name, &self.declared_inputs)
|
||||
});
|
||||
let cached = {
|
||||
let db = self.ctxt.db.deref().read();
|
||||
db.deref().prepare(self.fn_name, &self.declared_inputs)
|
||||
};
|
||||
|
||||
match cached {
|
||||
Some((ref disc_in, ref disc_out, ref res))
|
||||
|
@ -460,13 +461,12 @@ impl<'a, T:Send +
|
|||
WorkFromTask(prep, port) => {
|
||||
let (exe, v) = port.recv();
|
||||
let s = json_encode(&v);
|
||||
prep.ctxt.db.write(|db| {
|
||||
db.cache(prep.fn_name,
|
||||
&prep.declared_inputs,
|
||||
&exe.discovered_inputs,
|
||||
&exe.discovered_outputs,
|
||||
s)
|
||||
});
|
||||
let mut db = prep.ctxt.db.deref().write();
|
||||
db.deref_mut().cache(prep.fn_name,
|
||||
&prep.declared_inputs,
|
||||
&exe.discovered_inputs,
|
||||
&exe.discovered_outputs,
|
||||
s);
|
||||
v
|
||||
}
|
||||
}
|
||||
|
@ -496,7 +496,7 @@ fn test() {
|
|||
|
||||
let db_path = make_path(~"db.json");
|
||||
|
||||
let cx = Context::new(RWArc::new(Database::new(db_path)),
|
||||
let cx = Context::new(Arc::new(RWLock::new(Database::new(db_path))),
|
||||
Arc::new(TreeMap::new()));
|
||||
|
||||
let s = cx.with_prep("test1", |prep| {
|
||||
|
|
|
@ -18,36 +18,28 @@
|
|||
extern crate sync;
|
||||
extern crate time;
|
||||
|
||||
use sync::Arc;
|
||||
use sync::MutexArc;
|
||||
use sync::Future;
|
||||
use sync::{Arc, Future, Mutex};
|
||||
use std::os;
|
||||
use std::uint;
|
||||
|
||||
// A poor man's pipe.
|
||||
type pipe = MutexArc<Vec<uint> >;
|
||||
type pipe = Arc<Mutex<Vec<uint>>>;
|
||||
|
||||
fn send(p: &pipe, msg: uint) {
|
||||
unsafe {
|
||||
p.access_cond(|state, cond| {
|
||||
state.push(msg);
|
||||
cond.signal();
|
||||
})
|
||||
}
|
||||
let mut arr = p.lock();
|
||||
arr.push(msg);
|
||||
arr.cond.signal();
|
||||
}
|
||||
fn recv(p: &pipe) -> uint {
|
||||
unsafe {
|
||||
p.access_cond(|state, cond| {
|
||||
while state.is_empty() {
|
||||
cond.wait();
|
||||
}
|
||||
state.pop().unwrap()
|
||||
})
|
||||
let mut arr = p.lock();
|
||||
while arr.is_empty() {
|
||||
arr.cond.wait();
|
||||
}
|
||||
arr.pop().unwrap()
|
||||
}
|
||||
|
||||
fn init() -> (pipe,pipe) {
|
||||
let m = MutexArc::new(Vec::new());
|
||||
let m = Arc::new(Mutex::new(Vec::new()));
|
||||
((&m).clone(), m)
|
||||
}
|
||||
|
||||
|
|
|
@ -18,31 +18,29 @@
|
|||
extern crate sync;
|
||||
extern crate time;
|
||||
|
||||
use sync::RWArc;
|
||||
use sync::{RWLock, Arc};
|
||||
use sync::Future;
|
||||
use std::os;
|
||||
use std::uint;
|
||||
|
||||
// A poor man's pipe.
|
||||
type pipe = RWArc<Vec<uint> >;
|
||||
type pipe = Arc<RWLock<Vec<uint>>>;
|
||||
|
||||
fn send(p: &pipe, msg: uint) {
|
||||
p.write_cond(|state, cond| {
|
||||
state.push(msg);
|
||||
cond.signal();
|
||||
})
|
||||
let mut arr = p.write();
|
||||
arr.push(msg);
|
||||
arr.cond.signal();
|
||||
}
|
||||
fn recv(p: &pipe) -> uint {
|
||||
p.write_cond(|state, cond| {
|
||||
while state.is_empty() {
|
||||
cond.wait();
|
||||
}
|
||||
state.pop().unwrap()
|
||||
})
|
||||
let mut arr = p.write();
|
||||
while arr.is_empty() {
|
||||
arr.cond.wait();
|
||||
}
|
||||
arr.pop().unwrap()
|
||||
}
|
||||
|
||||
fn init() -> (pipe,pipe) {
|
||||
let x = RWArc::new(Vec::new());
|
||||
let x = Arc::new(RWLock::new(Vec::new()));
|
||||
((&x).clone(), x)
|
||||
}
|
||||
|
||||
|
|
|
@ -14,7 +14,8 @@ use std::from_str::FromStr;
|
|||
use std::iter::count;
|
||||
use std::cmp::min;
|
||||
use std::os;
|
||||
use sync::RWArc;
|
||||
use std::slice::from_elem;
|
||||
use sync::{Arc, RWLock};
|
||||
|
||||
fn A(i: uint, j: uint) -> f64 {
|
||||
((i + j) * (i + j + 1) / 2 + i + 1) as f64
|
||||
|
@ -28,17 +29,16 @@ fn dot(v: &[f64], u: &[f64]) -> f64 {
|
|||
sum
|
||||
}
|
||||
|
||||
fn mult(v: RWArc<Vec<f64>>,
|
||||
out: RWArc<Vec<f64>>,
|
||||
fn mult(v: Arc<RWLock<Vec<f64>>>, out: Arc<RWLock<Vec<f64>>>,
|
||||
f: fn(&Vec<f64>, uint) -> f64) {
|
||||
// We launch in different tasks the work to be done. To finish
|
||||
// We lanch in different tasks the work to be done. To finish
|
||||
// this fuction, we need to wait for the completion of every
|
||||
// tasks. To do that, we give to each tasks a wait_chan that we
|
||||
// drop at the end of the work. At the end of this function, we
|
||||
// wait until the channel hang up.
|
||||
let (tx, rx) = channel();
|
||||
|
||||
let len = out.read(|out| out.len());
|
||||
let len = out.read().len();
|
||||
let chunk = len / 100 + 1;
|
||||
for chk in count(0, chunk) {
|
||||
if chk >= len {break;}
|
||||
|
@ -47,8 +47,8 @@ fn mult(v: RWArc<Vec<f64>>,
|
|||
let out = out.clone();
|
||||
spawn(proc() {
|
||||
for i in range(chk, min(len, chk + chunk)) {
|
||||
let val = v.read(|v| f(v, i));
|
||||
out.write(|out| *out.get_mut(i) = val);
|
||||
let val = f(&*v.read(), i);
|
||||
*out.write().get_mut(i) = val;
|
||||
}
|
||||
drop(tx)
|
||||
});
|
||||
|
@ -67,7 +67,7 @@ fn mult_Av_impl(v: &Vec<f64> , i: uint) -> f64 {
|
|||
sum
|
||||
}
|
||||
|
||||
fn mult_Av(v: RWArc<Vec<f64> >, out: RWArc<Vec<f64> >) {
|
||||
fn mult_Av(v: Arc<RWLock<Vec<f64>>>, out: Arc<RWLock<Vec<f64>>>) {
|
||||
mult(v, out, mult_Av_impl);
|
||||
}
|
||||
|
||||
|
@ -79,11 +79,12 @@ fn mult_Atv_impl(v: &Vec<f64> , i: uint) -> f64 {
|
|||
sum
|
||||
}
|
||||
|
||||
fn mult_Atv(v: RWArc<Vec<f64> >, out: RWArc<Vec<f64> >) {
|
||||
fn mult_Atv(v: Arc<RWLock<Vec<f64>>>, out: Arc<RWLock<Vec<f64>>>) {
|
||||
mult(v, out, mult_Atv_impl);
|
||||
}
|
||||
|
||||
fn mult_AtAv(v: RWArc<Vec<f64> >, out: RWArc<Vec<f64> >, tmp: RWArc<Vec<f64> >) {
|
||||
fn mult_AtAv(v: Arc<RWLock<Vec<f64>>>, out: Arc<RWLock<Vec<f64>>>,
|
||||
tmp: Arc<RWLock<Vec<f64>>>) {
|
||||
mult_Av(v, tmp.clone());
|
||||
mult_Atv(tmp, out);
|
||||
}
|
||||
|
@ -97,16 +98,16 @@ fn main() {
|
|||
} else {
|
||||
FromStr::from_str(args[1]).unwrap()
|
||||
};
|
||||
let u = RWArc::new(Vec::from_elem(n, 1.));
|
||||
let v = RWArc::new(Vec::from_elem(n, 1.));
|
||||
let tmp = RWArc::new(Vec::from_elem(n, 1.));
|
||||
let u = Arc::new(RWLock::new(Vec::from_elem(n, 1.)));
|
||||
let v = Arc::new(RWLock::new(Vec::from_elem(n, 1.)));
|
||||
let tmp = Arc::new(RWLock::new(Vec::from_elem(n, 1.)));
|
||||
for _ in range(0, 10) {
|
||||
mult_AtAv(u.clone(), v.clone(), tmp.clone());
|
||||
mult_AtAv(v.clone(), u.clone(), tmp.clone());
|
||||
}
|
||||
|
||||
u.read(|u| v.read(|v| {
|
||||
println!("{:.9f}",
|
||||
(dot(u.as_slice(), v.as_slice()) / dot(v.as_slice(), v.as_slice())).sqrt());
|
||||
}))
|
||||
let u = u.read();
|
||||
let v = v.read();
|
||||
println!("{:.9f}", (dot(u.as_slice(), v.as_slice()) /
|
||||
dot(v.as_slice(), v.as_slice())).sqrt());
|
||||
}
|
||||
|
|
|
@ -1,17 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
extern crate sync;
|
||||
use sync::RWArc;
|
||||
|
||||
fn main() {
|
||||
let arc1 = RWArc::new(true);
|
||||
let _arc2 = RWArc::new(arc1); //~ ERROR instantiating a type parameter with an incompatible type
|
||||
}
|
|
@ -1,19 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of return value does not outlive the function call
|
||||
extern crate sync;
|
||||
use sync::RWArc;
|
||||
fn main() {
|
||||
let x = ~RWArc::new(1);
|
||||
let mut y = None;
|
||||
x.write_cond(|_one, cond| y = Some(cond));
|
||||
y.unwrap().wait();
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
extern crate sync;
|
||||
use sync::RWArc;
|
||||
fn main() {
|
||||
let x = ~RWArc::new(1);
|
||||
let mut y = None;
|
||||
x.write_downgrade(|write_mode| {
|
||||
y = Some(x.downgrade(write_mode));
|
||||
//~^ ERROR cannot infer
|
||||
});
|
||||
y.unwrap();
|
||||
// Adding this line causes a method unification failure instead
|
||||
// (&option::unwrap(y)).read(|state| { assert!(*state == 1); })
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
extern crate sync;
|
||||
use sync::RWArc;
|
||||
fn main() {
|
||||
let x = ~RWArc::new(1);
|
||||
let mut y = None; //~ ERROR lifetime of variable does not enclose its declaration
|
||||
x.write(|one| y = Some(one));
|
||||
*y.unwrap() = 2;
|
||||
//~^ ERROR lifetime of return value does not outlive the function call
|
||||
//~^^ ERROR dereference of reference outside its lifetime
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of variable does not enclose its declaration
|
||||
extern crate sync;
|
||||
use sync::RWArc;
|
||||
fn main() {
|
||||
let x = ~RWArc::new(1);
|
||||
let mut y = None;
|
||||
x.write_downgrade(|write_mode| {
|
||||
(&write_mode).write_cond(|_one, cond| {
|
||||
y = Some(cond);
|
||||
})
|
||||
});
|
||||
y.unwrap().wait();
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of variable does not enclose its declaration
|
||||
extern crate sync;
|
||||
use sync::RWArc;
|
||||
fn main() {
|
||||
let x = ~RWArc::new(1);
|
||||
let mut y = None;
|
||||
x.write_downgrade(|write_mode| y = Some(write_mode));
|
||||
y.unwrap();
|
||||
// Adding this line causes a method unification failure instead
|
||||
// (&option::unwrap(y)).write(|state| { assert!(*state == 1); })
|
||||
}
|
|
@ -17,7 +17,7 @@ use sync::Arc;
|
|||
struct A { y: Arc<int>, x: Arc<int> }
|
||||
|
||||
impl Drop for A {
|
||||
fn drop(&mut self) { println!("x={:?}", self.x.get()); }
|
||||
fn drop(&mut self) { println!("x={}", *self.x); }
|
||||
}
|
||||
fn main() {
|
||||
let a = A { y: Arc::new(1), x: Arc::new(2) };
|
||||
|
|
|
@ -20,11 +20,10 @@ fn main() {
|
|||
let arc_v = Arc::new(v);
|
||||
|
||||
task::spawn(proc() {
|
||||
let v = arc_v.get();
|
||||
assert_eq!(*v.get(3), 4);
|
||||
assert_eq!(*arc_v.get(3), 4);
|
||||
});
|
||||
|
||||
assert_eq!(*(arc_v.get()).get(2), 3);
|
||||
assert_eq!(*arc_v.get(2), 3);
|
||||
|
||||
println!("{:?}", arc_v);
|
||||
println!("{}", *arc_v);
|
||||
}
|
||||
|
|
|
@ -18,11 +18,10 @@ fn main() {
|
|||
let arc_v = Arc::new(v);
|
||||
|
||||
task::spawn(proc() {
|
||||
let v = arc_v.get();
|
||||
assert_eq!(*v.get(3), 4);
|
||||
assert_eq!(*arc_v.get(3), 4);
|
||||
});
|
||||
|
||||
assert_eq!(*(arc_v.get()).get(2), 3); //~ ERROR use of moved value: `arc_v`
|
||||
assert_eq!(*arc_v.get(2), 3); //~ ERROR use of moved value: `arc_v`
|
||||
|
||||
println!("{:?}", arc_v); //~ ERROR use of moved value: `arc_v`
|
||||
println!("{}", *arc_v); //~ ERROR use of moved value: `arc_v`
|
||||
}
|
||||
|
|
|
@ -23,7 +23,7 @@ fn foo(blk: proc()) {
|
|||
fn main() {
|
||||
let x = Arc::new(true);
|
||||
foo(proc() {
|
||||
assert!(*x.get());
|
||||
assert!(*x);
|
||||
drop(x);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -23,7 +23,7 @@ fn foo(blk: once ||) {
|
|||
fn main() {
|
||||
let x = Arc::new(true);
|
||||
foo(|| {
|
||||
assert!(*x.get());
|
||||
assert!(*x);
|
||||
drop(x);
|
||||
})
|
||||
}
|
||||
|
|
|
@ -22,7 +22,7 @@ fn foo(blk: ||) {
|
|||
fn main() {
|
||||
let x = Arc::new(true);
|
||||
foo(|| {
|
||||
assert!(*x.get());
|
||||
assert!(*x);
|
||||
drop(x); //~ ERROR cannot move out of captured outer variable
|
||||
})
|
||||
}
|
||||
|
|
|
@ -1,22 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of variable does not enclose its declaration
|
||||
extern crate sync;
|
||||
use sync::Mutex;
|
||||
|
||||
fn main() {
|
||||
let m = ~sync::Mutex::new();
|
||||
let mut cond = None;
|
||||
m.lock_cond(|c| {
|
||||
cond = Some(c);
|
||||
});
|
||||
cond.unwrap().signal();
|
||||
}
|
|
@ -1,21 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of method receiver does not outlive the method call
|
||||
extern crate sync;
|
||||
use sync::RWLock;
|
||||
fn main() {
|
||||
let x = ~RWLock::new();
|
||||
let mut y = None;
|
||||
x.write_cond(|cond| {
|
||||
y = Some(cond);
|
||||
});
|
||||
y.unwrap().wait();
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: cannot infer
|
||||
extern crate sync;
|
||||
use sync::RWLock;
|
||||
fn main() {
|
||||
let x = ~RWLock::new();
|
||||
let mut y = None;
|
||||
x.write_downgrade(|write_mode| {
|
||||
y = Some(x.downgrade(write_mode));
|
||||
})
|
||||
// Adding this line causes a method unification failure instead
|
||||
// (&option::unwrap(y)).read(proc() { });
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of variable does not enclose its declaration
|
||||
extern crate sync;
|
||||
use sync::RWLock;
|
||||
fn main() {
|
||||
let x = ~RWLock::new();
|
||||
let mut y = None;
|
||||
x.write_downgrade(|write_mode| {
|
||||
(&write_mode).write_cond(|cond| {
|
||||
y = Some(cond);
|
||||
})
|
||||
});
|
||||
y.unwrap().wait();
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
|
||||
// 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.
|
||||
|
||||
// error-pattern: lifetime of variable does not enclose its declaration
|
||||
extern crate sync;
|
||||
use sync::RWLock;
|
||||
fn main() {
|
||||
let x = ~RWLock::new();
|
||||
let mut y = None;
|
||||
x.write_downgrade(|write_mode| {
|
||||
y = Some(write_mode);
|
||||
});
|
||||
// Adding this line causes a method unification failure instead
|
||||
// (&option::unwrap(y)).write(proc() { })
|
||||
}
|
|
@ -23,7 +23,7 @@ fn foo(blk: proc()) {
|
|||
pub fn main() {
|
||||
let x = Arc::new(true);
|
||||
foo(proc() {
|
||||
assert!(*x.get());
|
||||
assert!(*x);
|
||||
drop(x);
|
||||
});
|
||||
}
|
||||
|
|
|
@ -23,7 +23,7 @@ fn foo(blk: once ||) {
|
|||
pub fn main() {
|
||||
let x = Arc::new(true);
|
||||
foo(|| {
|
||||
assert!(*x.get());
|
||||
assert!(*x);
|
||||
drop(x);
|
||||
})
|
||||
}
|
||||
|
|
|
@ -85,20 +85,20 @@ pub fn main() {
|
|||
|
||||
fn check_legs(arc: Arc<Vec<~Pet:Share+Send>>) {
|
||||
let mut legs = 0;
|
||||
for pet in arc.get().iter() {
|
||||
for pet in arc.iter() {
|
||||
legs += pet.num_legs();
|
||||
}
|
||||
assert!(legs == 12);
|
||||
}
|
||||
fn check_names(arc: Arc<Vec<~Pet:Share+Send>>) {
|
||||
for pet in arc.get().iter() {
|
||||
for pet in arc.iter() {
|
||||
pet.name(|name| {
|
||||
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
|
||||
})
|
||||
}
|
||||
}
|
||||
fn check_pedigree(arc: Arc<Vec<~Pet:Share+Send>>) {
|
||||
for pet in arc.get().iter() {
|
||||
for pet in arc.iter() {
|
||||
assert!(pet.of_good_pedigree());
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue