about summary refs log tree commit diff
path: root/src/libstd/sync
diff options
context:
space:
mode:
authorSimonas Kazlauskas <git@kazlauskas.me>2015-04-04 00:46:54 +0300
committerSimonas Kazlauskas <git@kazlauskas.me>2015-04-08 19:42:16 +0300
commit45aa6c8d1bc2f7863c92da6643de4642bb2d83bf (patch)
tree53f8648a696dc49072ceef53c36974f6fc599515 /src/libstd/sync
parent80def6c2447d23a624e611417f24cf0ab2a5a676 (diff)
downloadrust-45aa6c8d1bc2f7863c92da6643de4642bb2d83bf.tar.gz
rust-45aa6c8d1bc2f7863c92da6643de4642bb2d83bf.zip
Implement reentrant mutexes and make stdio use them
write_fmt calls write for each formatted field. The default implementation of write_fmt is used,
which will call write on not-yet-locked stdout (and write locking after), therefore making print!
in multithreaded environment still interleave contents of two separate prints.

This patch implements reentrant mutexes, changes stdio handles to use these mutexes and overrides
write_fmt to lock the stdio handle for the whole duration of the call.
Diffstat (limited to 'src/libstd/sync')
-rw-r--r--src/libstd/sync/condvar.rs6
-rw-r--r--src/libstd/sync/mod.rs13
-rw-r--r--src/libstd/sync/mutex.rs6
-rw-r--r--src/libstd/sync/poison.rs187
-rw-r--r--src/libstd/sync/rwlock.rs4
5 files changed, 14 insertions, 202 deletions
diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs
index a7d8b287a64..654b33f1a57 100644
--- a/src/libstd/sync/condvar.rs
+++ b/src/libstd/sync/condvar.rs
@@ -11,12 +11,12 @@
 use prelude::v1::*;
 
 use sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
-use sync::poison::{self, LockResult};
-use sys::time::SteadyTime;
+use sync::{mutex, MutexGuard, PoisonError};
 use sys_common::condvar as sys;
 use sys_common::mutex as sys_mutex;
+use sys_common::poison::{self, LockResult};
+use sys::time::SteadyTime;
 use time::Duration;
-use sync::{mutex, MutexGuard, PoisonError};
 
 /// A Condition Variable
 ///
diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs
index a5259a00390..91e9714fbef 100644
--- a/src/libstd/sync/mod.rs
+++ b/src/libstd/sync/mod.rs
@@ -20,15 +20,15 @@
 pub use alloc::arc::{Arc, Weak};
 pub use core::atomic;
 
-pub use self::mutex::{Mutex, MutexGuard, StaticMutex};
-pub use self::mutex::MUTEX_INIT;
-pub use self::rwlock::{RwLock, StaticRwLock, RW_LOCK_INIT};
-pub use self::rwlock::{RwLockReadGuard, RwLockWriteGuard};
+pub use self::barrier::{Barrier, BarrierWaitResult};
 pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT};
+pub use self::mutex::MUTEX_INIT;
+pub use self::mutex::{Mutex, MutexGuard, StaticMutex};
 pub use self::once::{Once, ONCE_INIT};
+pub use sys_common::poison::{PoisonError, TryLockError, TryLockResult, LockResult};
+pub use self::rwlock::{RwLockReadGuard, RwLockWriteGuard};
+pub use self::rwlock::{RwLock, StaticRwLock, RW_LOCK_INIT};
 pub use self::semaphore::{Semaphore, SemaphoreGuard};
-pub use self::barrier::{Barrier, BarrierWaitResult};
-pub use self::poison::{PoisonError, TryLockError, TryLockResult, LockResult};
 
 pub use self::future::Future;
 
@@ -39,6 +39,5 @@ mod condvar;
 mod future;
 mod mutex;
 mod once;
-mod poison;
 mod rwlock;
 mod semaphore;
diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs
index 16e7f265412..46fb20cd6a2 100644
--- a/src/libstd/sync/mutex.rs
+++ b/src/libstd/sync/mutex.rs
@@ -11,11 +11,11 @@
 use prelude::v1::*;
 
 use cell::UnsafeCell;
+use fmt;
 use marker;
 use ops::{Deref, DerefMut};
-use sync::poison::{self, TryLockError, TryLockResult, LockResult};
 use sys_common::mutex as sys;
-use fmt;
+use sys_common::poison::{self, TryLockError, TryLockResult, LockResult};
 
 /// A mutual exclusion primitive useful for protecting shared data
 ///
@@ -212,7 +212,7 @@ impl<T> Mutex<T> {
 
     /// Attempts to acquire this lock.
     ///
-    /// If the lock could not be acquired at this time, then `None` is returned.
+    /// If the lock could not be acquired at this time, then `Err` is returned.
     /// Otherwise, an RAII guard is returned. The lock will be unlocked when the
     /// guard is dropped.
     ///
diff --git a/src/libstd/sync/poison.rs b/src/libstd/sync/poison.rs
deleted file mode 100644
index 347cd0b464e..00000000000
--- a/src/libstd/sync/poison.rs
+++ /dev/null
@@ -1,187 +0,0 @@
-// Copyright 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.
-
-use prelude::v1::*;
-
-use cell::UnsafeCell;
-use error::{Error};
-use fmt;
-use thread;
-
-pub struct Flag { failed: UnsafeCell<bool> }
-
-// This flag is only ever accessed with a lock previously held. Note that this
-// a totally private structure.
-unsafe impl Send for Flag {}
-unsafe impl Sync for Flag {}
-
-pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };
-
-impl Flag {
-    #[inline]
-    pub fn borrow(&self) -> LockResult<Guard> {
-        let ret = Guard { panicking: thread::panicking() };
-        if unsafe { *self.failed.get() } {
-            Err(PoisonError::new(ret))
-        } else {
-            Ok(ret)
-        }
-    }
-
-    #[inline]
-    pub fn done(&self, guard: &Guard) {
-        if !guard.panicking && thread::panicking() {
-            unsafe { *self.failed.get() = true; }
-        }
-    }
-
-    #[inline]
-    pub fn get(&self) -> bool {
-        unsafe { *self.failed.get() }
-    }
-}
-
-pub struct Guard {
-    panicking: bool,
-}
-
-/// A type of error which can be returned whenever a lock is acquired.
-///
-/// Both Mutexes and RwLocks are poisoned whenever a task fails while the lock
-/// is held. The precise semantics for when a lock is poisoned is documented on
-/// each lock, but once a lock is poisoned then all future acquisitions will
-/// return this error.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub struct PoisonError<T> {
-    guard: T,
-}
-
-/// An enumeration of possible errors which can occur while calling the
-/// `try_lock` method.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub enum TryLockError<T> {
-    /// The lock could not be acquired because another task failed while holding
-    /// the lock.
-    #[stable(feature = "rust1", since = "1.0.0")]
-    Poisoned(PoisonError<T>),
-    /// The lock could not be acquired at this time because the operation would
-    /// otherwise block.
-    #[stable(feature = "rust1", since = "1.0.0")]
-    WouldBlock,
-}
-
-/// A type alias for the result of a lock method which can be poisoned.
-///
-/// The `Ok` variant of this result indicates that the primitive was not
-/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
-/// that the primitive was poisoned. Note that the `Err` variant *also* carries
-/// the associated guard, and it can be acquired through the `into_inner`
-/// method.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
-
-/// A type alias for the result of a nonblocking locking method.
-///
-/// For more information, see `LockResult`. A `TryLockResult` doesn't
-/// necessarily hold the associated guard in the `Err` type as the lock may not
-/// have been acquired for other reasons.
-#[stable(feature = "rust1", since = "1.0.0")]
-pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> fmt::Debug for PoisonError<T> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        "PoisonError { inner: .. }".fmt(f)
-    }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> fmt::Display for PoisonError<T> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        "poisoned lock: another task failed inside".fmt(f)
-    }
-}
-
-impl<T: Send> Error for PoisonError<T> {
-    fn description(&self) -> &str {
-        "poisoned lock: another task failed inside"
-    }
-}
-
-impl<T> PoisonError<T> {
-    /// Create a `PoisonError`.
-    #[unstable(feature = "std_misc")]
-    pub fn new(guard: T) -> PoisonError<T> {
-        PoisonError { guard: guard }
-    }
-
-    /// Consumes this error indicating that a lock is poisoned, returning the
-    /// underlying guard to allow access regardless.
-    #[unstable(feature = "std_misc")]
-    pub fn into_inner(self) -> T { self.guard }
-
-    /// Reaches into this error indicating that a lock is poisoned, returning a
-    /// reference to the underlying guard to allow access regardless.
-    #[unstable(feature = "std_misc")]
-    pub fn get_ref(&self) -> &T { &self.guard }
-
-    /// Reaches into this error indicating that a lock is poisoned, returning a
-    /// mutable reference to the underlying guard to allow access regardless.
-    #[unstable(feature = "std_misc")]
-    pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
-}
-
-impl<T> From<PoisonError<T>> for TryLockError<T> {
-    fn from(err: PoisonError<T>) -> TryLockError<T> {
-        TryLockError::Poisoned(err)
-    }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T> fmt::Debug for TryLockError<T> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        match *self {
-            TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
-            TryLockError::WouldBlock => "WouldBlock".fmt(f)
-        }
-    }
-}
-
-#[stable(feature = "rust1", since = "1.0.0")]
-impl<T: Send> fmt::Display for TryLockError<T> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        self.description().fmt(f)
-    }
-}
-
-impl<T: Send> Error for TryLockError<T> {
-    fn description(&self) -> &str {
-        match *self {
-            TryLockError::Poisoned(ref p) => p.description(),
-            TryLockError::WouldBlock => "try_lock failed because the operation would block"
-        }
-    }
-
-    fn cause(&self) -> Option<&Error> {
-        match *self {
-            TryLockError::Poisoned(ref p) => Some(p),
-            _ => None
-        }
-    }
-}
-
-pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
-                           -> LockResult<U>
-                           where F: FnOnce(T) -> U {
-    match result {
-        Ok(t) => Ok(f(t)),
-        Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))
-    }
-}
diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs
index d70350bc7d6..eb6d46a5dda 100644
--- a/src/libstd/sync/rwlock.rs
+++ b/src/libstd/sync/rwlock.rs
@@ -11,11 +11,11 @@
 use prelude::v1::*;
 
 use cell::UnsafeCell;
+use fmt;
 use marker;
 use ops::{Deref, DerefMut};
-use sync::poison::{self, LockResult, TryLockError, TryLockResult};
+use sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
 use sys_common::rwlock as sys;
-use fmt;
 
 /// A reader-writer lock
 ///