diff options
| author | bors <bors@rust-lang.org> | 2014-12-30 08:02:39 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-12-30 08:02:39 +0000 |
| commit | d2368c3c11ddab9d812c4ddec2e44579326ad347 (patch) | |
| tree | b976bc0eb040da67646a9d99bb9b901cb9f55abd /src/libstd | |
| parent | fea5aa656ff4349f4d3e1fea1447d26986762ae1 (diff) | |
| parent | 470ae101d6e26a6ce07292b7fca6eaed527451c7 (diff) | |
| download | rust-d2368c3c11ddab9d812c4ddec2e44579326ad347.tar.gz rust-d2368c3c11ddab9d812c4ddec2e44579326ad347.zip | |
auto merge of #20320 : alexcrichton/rust/rollup, r=alexcrichton
Diffstat (limited to 'src/libstd')
53 files changed, 851 insertions, 630 deletions
diff --git a/src/libstd/bitflags.rs b/src/libstd/bitflags.rs index 5dd76047779..a46b8a9ad90 100644 --- a/src/libstd/bitflags.rs +++ b/src/libstd/bitflags.rs @@ -104,6 +104,10 @@ /// - `empty`: an empty set of flags /// - `all`: the set of all flags /// - `bits`: the raw value of the flags currently stored +/// - `from_bits`: convert from underlying bit representation, unless that +/// representation contains bits that do not correspond to a flag +/// - `from_bits_truncate`: convert from underlying bit representation, dropping +/// any bits that do not correspond to flags /// - `is_empty`: `true` if no flags are currently stored /// - `is_all`: `true` if all flags are currently set /// - `intersects`: `true` if there are flags common to both `self` and `other` diff --git a/src/libstd/c_str.rs b/src/libstd/c_str.rs index ffe19203769..f28abcc10cf 100644 --- a/src/libstd/c_str.rs +++ b/src/libstd/c_str.rs @@ -537,7 +537,8 @@ pub unsafe fn from_c_multistring<F>(buf: *const libc::c_char, #[cfg(test)] mod tests { use super::*; - use prelude::*; + use prelude::{spawn, Some, None, Option, FnOnce, ToString, CloneSliceExt}; + use prelude::{Clone, PtrExt, Iterator, SliceExt, StrExt}; use ptr; use thread::Thread; use libc; diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index f4338815f75..0aa51ee66ed 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -40,7 +40,7 @@ use mem; use ops::{Drop, FnOnce}; use option::Option; use option::Option::{Some, None}; -use ptr::RawPtr; +use ptr::PtrExt; use ptr; use raw; use slice::AsSlice; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index d749cd77cef..7b7473b2c99 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -264,27 +264,35 @@ fn test_resize_policy() { /// } /// ``` /// -/// The easiest way to use `HashMap` with a custom type is to derive `Eq` and `Hash`. +/// The easiest way to use `HashMap` with a custom type as key is to derive `Eq` and `Hash`. /// We must also derive `PartialEq`. /// /// ``` /// use std::collections::HashMap; /// /// #[deriving(Hash, Eq, PartialEq, Show)] -/// struct Viking<'a> { -/// name: &'a str, -/// power: uint, +/// struct Viking { +/// name: String, +/// country: String, /// } /// +/// impl Viking { +/// /// Create a new Viking. +/// fn new(name: &str, country: &str) -> Viking { +/// Viking { name: name.to_string(), country: country.to_string() } +/// } +/// } +/// +/// // Use a HashMap to store the vikings' health points. /// let mut vikings = HashMap::new(); /// -/// vikings.insert("Norway", Viking { name: "Einar", power: 9u }); -/// vikings.insert("Denmark", Viking { name: "Olaf", power: 4u }); -/// vikings.insert("Iceland", Viking { name: "Harald", power: 8u }); +/// vikings.insert(Viking::new("Einar", "Norway"), 25u); +/// vikings.insert(Viking::new("Olaf", "Denmark"), 24u); +/// vikings.insert(Viking::new("Harald", "Iceland"), 12u); /// -/// // Use derived implementation to print the vikings. -/// for (land, viking) in vikings.iter() { -/// println!("{} at {}", viking, land); +/// // Use derived implementation to print the status of the vikings. +/// for (viking, health) in vikings.iter() { +/// println!("{} has {} hp", viking, health); /// } /// ``` #[deriving(Clone)] @@ -888,8 +896,8 @@ impl<K: Eq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { /// } /// ``` #[unstable = "matches collection reform specification, waiting for dust to settle"] - pub fn iter(&self) -> Entries<K, V> { - Entries { inner: self.table.iter() } + pub fn iter(&self) -> Iter<K, V> { + Iter { inner: self.table.iter() } } /// An iterator visiting all key-value pairs in arbitrary order, @@ -1305,8 +1313,8 @@ impl<K: Hash<S> + Eq, Sized? Q, V, S, H: Hasher<S>> IndexMut<Q, V> for HashMap<K } /// HashMap iterator -pub struct Entries<'a, K: 'a, V: 'a> { - inner: table::Entries<'a, K, V> +pub struct Iter<'a, K: 'a, V: 'a> { + inner: table::Iter<'a, K, V> } /// HashMap mutable values iterator @@ -1326,12 +1334,12 @@ pub struct IntoIter<K, V> { /// HashMap keys iterator pub struct Keys<'a, K: 'a, V: 'a> { - inner: Map<(&'a K, &'a V), &'a K, Entries<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> + inner: Map<(&'a K, &'a V), &'a K, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a K> } /// HashMap values iterator pub struct Values<'a, K: 'a, V: 'a> { - inner: Map<(&'a K, &'a V), &'a V, Entries<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> + inner: Map<(&'a K, &'a V), &'a V, Iter<'a, K, V>, fn((&'a K, &'a V)) -> &'a V> } /// HashMap drain iterator @@ -1373,7 +1381,7 @@ enum VacantEntryState<K, V, M> { NoElem(EmptyBucket<K, V, M>), } -impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> { +impl<'a, K, V> Iterator<(&'a K, &'a V)> for Iter<'a, K, V> { #[inline] fn next(&mut self) -> Option<(&'a K, &'a V)> { self.inner.next() } #[inline] fn size_hint(&self) -> (uint, Option<uint>) { self.inner.size_hint() } } diff --git a/src/libstd/collections/hash/table.rs b/src/libstd/collections/hash/table.rs index 3ae3a8ffbad..f76b8ac3326 100644 --- a/src/libstd/collections/hash/table.rs +++ b/src/libstd/collections/hash/table.rs @@ -23,7 +23,7 @@ use num::{Int, UnsignedInt}; use ops::{Deref, DerefMut, Drop}; use option::Option; use option::Option::{Some, None}; -use ptr::{Unique, RawPtr, copy_nonoverlapping_memory, zero_memory}; +use ptr::{Unique, PtrExt, copy_nonoverlapping_memory, zero_memory}; use ptr; use rt::heap::{allocate, deallocate}; @@ -657,8 +657,8 @@ impl<K, V> RawTable<K, V> { } } - pub fn iter(&self) -> Entries<K, V> { - Entries { + pub fn iter(&self) -> Iter<K, V> { + Iter { iter: self.raw_buckets(), elems_left: self.size(), } @@ -770,7 +770,7 @@ impl<'a, K, V> Iterator<(K, V)> for RevMoveBuckets<'a, K, V> { } /// Iterator over shared references to entries in a table. -pub struct Entries<'a, K: 'a, V: 'a> { +pub struct Iter<'a, K: 'a, V: 'a> { iter: RawBuckets<'a, K, V>, elems_left: uint, } @@ -793,7 +793,7 @@ pub struct Drain<'a, K: 'a, V: 'a> { iter: RawBuckets<'static, K, V>, } -impl<'a, K, V> Iterator<(&'a K, &'a V)> for Entries<'a, K, V> { +impl<'a, K, V> Iterator<(&'a K, &'a V)> for Iter<'a, K, V> { fn next(&mut self) -> Option<(&'a K, &'a V)> { self.iter.next().map(|bucket| { self.elems_left -= 1; diff --git a/src/libstd/comm/mod.rs b/src/libstd/comm/mod.rs index c85bea87218..a405627aecc 100644 --- a/src/libstd/comm/mod.rs +++ b/src/libstd/comm/mod.rs @@ -181,7 +181,7 @@ // senders. Under the hood, however, there are actually three flavors of // channels in play. // -// * Oneshots - these channels are highly optimized for the one-send use case. +// * Flavor::Oneshots - these channels are highly optimized for the one-send use case. // They contain as few atomics as possible and involve one and // exactly one allocation. // * Streams - these channels are optimized for the non-shared use case. They @@ -316,7 +316,6 @@ use core::prelude::*; pub use self::TryRecvError::*; pub use self::TrySendError::*; -use self::Flavor::*; use alloc::arc::Arc; use core::kinds; @@ -337,7 +336,8 @@ macro_rules! test { use super::*; use comm::*; use thread::Thread; - use prelude::*; + use prelude::{Ok, Err, spawn, range, drop, Box, Some, None, Option}; + use prelude::{Vec, Buffer, from_str, Clone}; $(#[$a])* #[test] fn f() { $b } } @@ -478,7 +478,7 @@ impl<T> UnsafeFlavor<T> for Receiver<T> { #[unstable] pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) { let a = Arc::new(RacyCell::new(oneshot::Packet::new())); - (Sender::new(Oneshot(a.clone())), Receiver::new(Oneshot(a))) + (Sender::new(Flavor::Oneshot(a.clone())), Receiver::new(Flavor::Oneshot(a))) } /// Creates a new synchronous, bounded channel. @@ -518,7 +518,7 @@ pub fn channel<T: Send>() -> (Sender<T>, Receiver<T>) { of channel that is is creating"] pub fn sync_channel<T: Send>(bound: uint) -> (SyncSender<T>, Receiver<T>) { let a = Arc::new(RacyCell::new(sync::Packet::new(bound))); - (SyncSender::new(a.clone()), Receiver::new(Sync(a))) + (SyncSender::new(a.clone()), Receiver::new(Flavor::Sync(a))) } //////////////////////////////////////////////////////////////////////////////// @@ -592,7 +592,7 @@ impl<T: Send> Sender<T> { #[unstable = "this function may be renamed to send() in the future"] pub fn send_opt(&self, t: T) -> Result<(), T> { let (new_inner, ret) = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { unsafe { let p = p.get(); if !(*p).sent() { @@ -600,7 +600,7 @@ impl<T: Send> Sender<T> { } else { let a = Arc::new(RacyCell::new(stream::Packet::new())); - match (*p).upgrade(Receiver::new(Stream(a.clone()))) { + match (*p).upgrade(Receiver::new(Flavor::Stream(a.clone()))) { oneshot::UpSuccess => { let ret = (*a.get()).send(t); (a, ret) @@ -618,13 +618,13 @@ impl<T: Send> Sender<T> { } } } - Stream(ref p) => return unsafe { (*p.get()).send(t) }, - Shared(ref p) => return unsafe { (*p.get()).send(t) }, - Sync(..) => unreachable!(), + Flavor::Stream(ref p) => return unsafe { (*p.get()).send(t) }, + Flavor::Shared(ref p) => return unsafe { (*p.get()).send(t) }, + Flavor::Sync(..) => unreachable!(), }; unsafe { - let tmp = Sender::new(Stream(new_inner)); + let tmp = Sender::new(Flavor::Stream(new_inner)); mem::swap(self.inner_mut(), tmp.inner_mut()); } return ret; @@ -635,42 +635,42 @@ impl<T: Send> Sender<T> { impl<T: Send> Clone for Sender<T> { fn clone(&self) -> Sender<T> { let (packet, sleeper, guard) = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) { + match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) { oneshot::UpSuccess | oneshot::UpDisconnected => (a, None, guard), oneshot::UpWoke(task) => (a, Some(task), guard) } } } - Stream(ref p) => { + Flavor::Stream(ref p) => { let a = Arc::new(RacyCell::new(shared::Packet::new())); unsafe { let guard = (*a.get()).postinit_lock(); - match (*p.get()).upgrade(Receiver::new(Shared(a.clone()))) { + match (*p.get()).upgrade(Receiver::new(Flavor::Shared(a.clone()))) { stream::UpSuccess | stream::UpDisconnected => (a, None, guard), stream::UpWoke(task) => (a, Some(task), guard), } } } - Shared(ref p) => { + Flavor::Shared(ref p) => { unsafe { (*p.get()).clone_chan(); } - return Sender::new(Shared(p.clone())); + return Sender::new(Flavor::Shared(p.clone())); } - Sync(..) => unreachable!(), + Flavor::Sync(..) => unreachable!(), }; unsafe { (*packet.get()).inherit_blocker(sleeper, guard); - let tmp = Sender::new(Shared(packet.clone())); + let tmp = Sender::new(Flavor::Shared(packet.clone())); mem::swap(self.inner_mut(), tmp.inner_mut()); } - Sender::new(Shared(packet)) + Sender::new(Flavor::Shared(packet)) } } @@ -678,10 +678,10 @@ impl<T: Send> Clone for Sender<T> { impl<T: Send> Drop for Sender<T> { fn drop(&mut self) { match *unsafe { self.inner_mut() } { - Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); }, - Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); }, - Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); }, - Sync(..) => unreachable!(), + Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_chan(); }, + Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_chan(); }, + Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_chan(); }, + Flavor::Sync(..) => unreachable!(), } } } @@ -827,7 +827,7 @@ impl<T: Send> Receiver<T> { pub fn try_recv(&self) -> Result<T, TryRecvError> { loop { let new_port = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), Err(oneshot::Empty) => return Err(Empty), @@ -835,7 +835,7 @@ impl<T: Send> Receiver<T> { Err(oneshot::Upgraded(rx)) => rx, } } - Stream(ref p) => { + Flavor::Stream(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), Err(stream::Empty) => return Err(Empty), @@ -843,14 +843,14 @@ impl<T: Send> Receiver<T> { Err(stream::Upgraded(rx)) => rx, } } - Shared(ref p) => { + Flavor::Shared(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), Err(shared::Empty) => return Err(Empty), Err(shared::Disconnected) => return Err(Disconnected), } } - Sync(ref p) => { + Flavor::Sync(ref p) => { match unsafe { (*p.get()).try_recv() } { Ok(t) => return Ok(t), Err(sync::Empty) => return Err(Empty), @@ -881,7 +881,7 @@ impl<T: Send> Receiver<T> { pub fn recv_opt(&self) -> Result<T, ()> { loop { let new_port = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(oneshot::Empty) => return unreachable!(), @@ -889,7 +889,7 @@ impl<T: Send> Receiver<T> { Err(oneshot::Upgraded(rx)) => rx, } } - Stream(ref p) => { + Flavor::Stream(ref p) => { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(stream::Empty) => return unreachable!(), @@ -897,14 +897,14 @@ impl<T: Send> Receiver<T> { Err(stream::Upgraded(rx)) => rx, } } - Shared(ref p) => { + Flavor::Shared(ref p) => { match unsafe { (*p.get()).recv() } { Ok(t) => return Ok(t), Err(shared::Empty) => return unreachable!(), Err(shared::Disconnected) => return Err(()), } } - Sync(ref p) => return unsafe { (*p.get()).recv() } + Flavor::Sync(ref p) => return unsafe { (*p.get()).recv() } }; unsafe { mem::swap(self.inner_mut(), new_port.inner_mut()); @@ -924,22 +924,22 @@ impl<T: Send> select::Packet for Receiver<T> { fn can_recv(&self) -> bool { loop { let new_port = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).can_recv() } { Ok(ret) => return ret, Err(upgrade) => upgrade, } } - Stream(ref p) => { + Flavor::Stream(ref p) => { match unsafe { (*p.get()).can_recv() } { Ok(ret) => return ret, Err(upgrade) => upgrade, } } - Shared(ref p) => { + Flavor::Shared(ref p) => { return unsafe { (*p.get()).can_recv() }; } - Sync(ref p) => { + Flavor::Sync(ref p) => { return unsafe { (*p.get()).can_recv() }; } }; @@ -953,24 +953,24 @@ impl<T: Send> select::Packet for Receiver<T> { fn start_selection(&self, mut token: SignalToken) -> StartResult { loop { let (t, new_port) = match *unsafe { self.inner() } { - Oneshot(ref p) => { + Flavor::Oneshot(ref p) => { match unsafe { (*p.get()).start_selection(token) } { oneshot::SelSuccess => return Installed, oneshot::SelCanceled => return Abort, oneshot::SelUpgraded(t, rx) => (t, rx), } } - Stream(ref p) => { + Flavor::Stream(ref p) => { match unsafe { (*p.get()).start_selection(token) } { stream::SelSuccess => return Installed, stream::SelCanceled => return Abort, stream::SelUpgraded(t, rx) => (t, rx), } } - Shared(ref p) => { + Flavor::Shared(ref p) => { return unsafe { (*p.get()).start_selection(token) }; } - Sync(ref p) => { + Flavor::Sync(ref p) => { return unsafe { (*p.get()).start_selection(token) }; } }; @@ -985,14 +985,14 @@ impl<T: Send> select::Packet for Receiver<T> { let mut was_upgrade = false; loop { let result = match *unsafe { self.inner() } { - Oneshot(ref p) => unsafe { (*p.get()).abort_selection() }, - Stream(ref p) => unsafe { + Flavor::Oneshot(ref p) => unsafe { (*p.get()).abort_selection() }, + Flavor::Stream(ref p) => unsafe { (*p.get()).abort_selection(was_upgrade) }, - Shared(ref p) => return unsafe { + Flavor::Shared(ref p) => return unsafe { (*p.get()).abort_selection(was_upgrade) }, - Sync(ref p) => return unsafe { + Flavor::Sync(ref p) => return unsafe { (*p.get()).abort_selection() }, }; @@ -1015,10 +1015,10 @@ impl<'a, T: Send> Iterator<T> for Messages<'a, T> { impl<T: Send> Drop for Receiver<T> { fn drop(&mut self) { match *unsafe { self.inner_mut() } { - Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); }, - Stream(ref mut p) => unsafe { (*p.get()).drop_port(); }, - Shared(ref mut p) => unsafe { (*p.get()).drop_port(); }, - Sync(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Oneshot(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Stream(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Shared(ref mut p) => unsafe { (*p.get()).drop_port(); }, + Flavor::Sync(ref mut p) => unsafe { (*p.get()).drop_port(); }, } } } @@ -1047,7 +1047,7 @@ unsafe impl<T> kinds::Sync for RacyCell<T> { } // Oh dear #[cfg(test)] mod test { use super::*; - use prelude::*; + use prelude::{spawn, range, Some, None, from_str, Clone, Str}; use os; pub fn stress_factor() -> uint { diff --git a/src/libstd/comm/shared.rs b/src/libstd/comm/shared.rs index 1022694e634..3f23ec5dc66 100644 --- a/src/libstd/comm/shared.rs +++ b/src/libstd/comm/shared.rs @@ -86,7 +86,7 @@ impl<T: Send> Packet<T> { // and that could cause problems on platforms where it is // represented by opaque data structure pub fn postinit_lock(&self) -> MutexGuard<()> { - self.select_lock.lock() + self.select_lock.lock().unwrap() } // This function is used at the creation of a shared packet to inherit a @@ -435,7 +435,7 @@ impl<T: Send> Packet<T> { // about looking at and dealing with to_wake. Once we have acquired the // lock, we are guaranteed that inherit_blocker is done. { - let _guard = self.select_lock.lock(); + let _guard = self.select_lock.lock().unwrap(); } // Like the stream implementation, we want to make sure that the count diff --git a/src/libstd/comm/sync.rs b/src/libstd/comm/sync.rs index 88338849965..82ec1814ebd 100644 --- a/src/libstd/comm/sync.rs +++ b/src/libstd/comm/sync.rs @@ -121,9 +121,9 @@ fn wait<'a, 'b, T: Send>(lock: &'a Mutex<State<T>>, NoneBlocked => {} _ => unreachable!(), } - drop(guard); // unlock - wait_token.wait(); // block - lock.lock() // relock + drop(guard); // unlock + wait_token.wait(); // block + lock.lock().unwrap() // relock } /// Wakes up a thread, dropping the lock at the correct time @@ -161,7 +161,7 @@ impl<T: Send> Packet<T> { fn acquire_send_slot(&self) -> MutexGuard<State<T>> { let mut node = Node { token: None, next: 0 as *mut Node }; loop { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); // are we ready to go? if guard.disconnected || guard.buf.size() < guard.buf.cap() { return guard; @@ -202,7 +202,7 @@ impl<T: Send> Packet<T> { } pub fn try_send(&self, t: T) -> Result<(), super::TrySendError<T>> { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); if guard.disconnected { Err(super::RecvDisconnected(t)) } else if guard.buf.size() == guard.buf.cap() { @@ -239,7 +239,7 @@ impl<T: Send> Packet<T> { // When reading this, remember that there can only ever be one receiver at // time. pub fn recv(&self) -> Result<T, ()> { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); // Wait for the buffer to have something in it. No need for a while loop // because we're the only receiver. @@ -258,7 +258,7 @@ impl<T: Send> Packet<T> { } pub fn try_recv(&self) -> Result<T, Failure> { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); // Easy cases first if guard.disconnected { return Err(Disconnected) } @@ -315,7 +315,7 @@ impl<T: Send> Packet<T> { } // Not much to do other than wake up a receiver if one's there - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); if guard.disconnected { return } guard.disconnected = true; match mem::replace(&mut guard.blocker, NoneBlocked) { @@ -326,7 +326,7 @@ impl<T: Send> Packet<T> { } pub fn drop_port(&self) { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); if guard.disconnected { return } guard.disconnected = true; @@ -372,14 +372,14 @@ impl<T: Send> Packet<T> { // If Ok, the value is whether this port has data, if Err, then the upgraded // port needs to be checked instead of this one. pub fn can_recv(&self) -> bool { - let guard = self.lock.lock(); + let guard = self.lock.lock().unwrap(); guard.disconnected || guard.buf.size() > 0 } // Attempts to start selection on this port. This can either succeed or fail // because there is data waiting. pub fn start_selection(&self, token: SignalToken) -> StartResult { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); if guard.disconnected || guard.buf.size() > 0 { Abort } else { @@ -397,7 +397,7 @@ impl<T: Send> Packet<T> { // // The return value indicates whether there's data on this port. pub fn abort_selection(&self) -> bool { - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); match mem::replace(&mut guard.blocker, NoneBlocked) { NoneBlocked => true, BlockedSender(token) => { @@ -413,7 +413,7 @@ impl<T: Send> Packet<T> { impl<T: Send> Drop for Packet<T> { fn drop(&mut self) { assert_eq!(self.channels.load(atomic::SeqCst), 0); - let mut guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); assert!(guard.queue.dequeue().is_none()); assert!(guard.canceled.is_none()); } diff --git a/src/libstd/error.rs b/src/libstd/error.rs index cd7d9aacc90..9a46a500a4b 100644 --- a/src/libstd/error.rs +++ b/src/libstd/error.rs @@ -81,6 +81,7 @@ use prelude::*; use str::Utf8Error; +use string::{FromUtf8Error, FromUtf16Error}; /// Base functionality for all errors in Rust. pub trait Error: Send { @@ -117,3 +118,12 @@ impl Error for Utf8Error { fn detail(&self) -> Option<String> { Some(self.to_string()) } } + +impl Error for FromUtf8Error { + fn description(&self) -> &str { "invalid utf-8" } + fn detail(&self) -> Option<String> { Some(self.to_string()) } +} + +impl Error for FromUtf16Error { + fn description(&self) -> &str { "invalid utf-16" } +} diff --git a/src/libstd/hash.rs b/src/libstd/hash.rs index 52e3c718b2d..737fef23c74 100644 --- a/src/libstd/hash.rs +++ b/src/libstd/hash.rs @@ -79,7 +79,7 @@ impl RandomSipHasher { /// Construct a new `RandomSipHasher` that is initialized with random keys. #[inline] pub fn new() -> RandomSipHasher { - let mut r = rand::task_rng(); + let mut r = rand::thread_rng(); let r0 = r.gen(); let r1 = r.gen(); RandomSipHasher { diff --git a/src/libstd/io/extensions.rs b/src/libstd/io/extensions.rs index c1f1a5b7869..e8765e3c231 100644 --- a/src/libstd/io/extensions.rs +++ b/src/libstd/io/extensions.rs @@ -22,7 +22,7 @@ use num::Int; use ops::FnOnce; use option::Option; use option::Option::{Some, None}; -use ptr::RawPtr; +use ptr::PtrExt; use result::Result::{Ok, Err}; use slice::{SliceExt, AsSlice}; diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index f2db2875ebf..caa6590bb28 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -1149,6 +1149,19 @@ mod test { } #[test] + fn mkdir_path_already_exists_error() { + use io::{IoError, PathAlreadyExists}; + + let tmpdir = tmpdir(); + let dir = &tmpdir.join("mkdir_error_twice"); + check!(mkdir(dir, io::USER_RWX)); + match mkdir(dir, io::USER_RWX) { + Err(IoError{kind:PathAlreadyExists,..}) => (), + _ => assert!(false) + }; + } + + #[test] fn recursive_mkdir() { let tmpdir = tmpdir(); let dir = tmpdir.join("d1/d2"); diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 20b1162d859..79327a29615 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -400,8 +400,8 @@ impl<'a> Buffer for BufReader<'a> { mod test { extern crate "test" as test_crate; use super::*; - use io::*; - use prelude::*; + use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek}; + use prelude::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt, IteratorExt, CloneSliceExt}; use io; use self::test_crate::Bencher; diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index e1f5efae79f..7a25360e695 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -935,7 +935,7 @@ impl<'a> Reader for &'a mut (Reader+'a) { // API yet. If so, it should be a method on Vec. unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] { use raw::Slice; - use ptr::RawPtr; + use ptr::PtrExt; assert!(start <= end); assert!(end <= v.capacity()); @@ -1724,7 +1724,7 @@ pub fn standard_error(kind: IoErrorKind) -> IoError { /// A mode specifies how a file should be opened or created. These modes are /// passed to `File::open_mode` and are used to control where the file is /// positioned when it is initially opened. -#[deriving(Copy)] +#[deriving(Copy, Clone, PartialEq, Eq)] pub enum FileMode { /// Opens a file positioned at the beginning. Open, @@ -1736,7 +1736,7 @@ pub enum FileMode { /// Access permissions with which the file should be opened. `File`s /// opened with `Read` will return an error if written to. -#[deriving(Copy)] +#[deriving(Copy, Clone, PartialEq, Eq)] pub enum FileAccess { /// Read-only access, requests to write will result in an error Read, @@ -1959,8 +1959,8 @@ impl fmt::Show for FilePermission { #[cfg(test)] mod tests { use self::BadReaderBehavior::*; - use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput}; - use prelude::*; + use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput, Writer}; + use prelude::{Ok, Vec, Buffer, CloneSliceExt}; use uint; #[deriving(Clone, PartialEq, Show)] diff --git a/src/libstd/io/net/pipe.rs b/src/libstd/io/net/pipe.rs index 4afc72cde71..93f37a8c98f 100644 --- a/src/libstd/io/net/pipe.rs +++ b/src/libstd/io/net/pipe.rs @@ -269,7 +269,7 @@ mod tests { use super::*; use io::*; use io::test::*; - use prelude::*; + use prelude::{Ok, Err, spawn, range, drop, Some, None, channel, Send, FnOnce, Clone}; use io::fs::PathExtensions; use time::Duration; diff --git a/src/libstd/io/net/tcp.rs b/src/libstd/io/net/tcp.rs index 6adb5387f2e..24cf06973cc 100644 --- a/src/libstd/io/net/tcp.rs +++ b/src/libstd/io/net/tcp.rs @@ -484,9 +484,12 @@ impl sys_common::AsInner<TcpAcceptorImp> for TcpAcceptor { mod test { use io::net::tcp::*; use io::net::ip::*; - use io::*; + use io::{EndOfFile, TimedOut, IoError, ShortWrite, OtherIoError, ConnectionAborted}; + use io::{ConnectionRefused, ConnectionReset, BrokenPipe, NotConnected}; + use io::{PermissionDenied, Listener, Acceptor}; use io::test::*; - use prelude::*; + use prelude::{Ok, Err, spawn, range, drop, Some, None, channel, Clone}; + use prelude::{Reader, Writer, IteratorExt}; // FIXME #11530 this fails on android because tests are run as root #[cfg_attr(any(windows, target_os = "android"), ignore)] diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index 5bf47dceb5a..1431067d4c6 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -250,9 +250,9 @@ impl Writer for UdpStream { mod test { use super::*; use io::net::ip::*; - use io::*; + use io::{ShortWrite, IoError, TimedOut, PermissionDenied}; use io::test::*; - use prelude::*; + use prelude::{Ok, Err, spawn, range, drop, Some, None, channel, Clone, Reader, Writer}; // FIXME #11530 this fails on android because tests are run as root #[cfg_attr(any(windows, target_os = "android"), ignore)] diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 93aa627ffba..b127507f048 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -745,8 +745,10 @@ mod tests { use super::*; use io::timer::*; - use io::*; - use prelude::*; + use io::{Truncate, Write, TimedOut, timer, process, FileNotFound}; + use prelude::{Ok, Err, spawn, range, drop, Box, Some, None, Option, Vec, Buffer}; + use prelude::{from_str, Path, String, channel, Reader, Writer, Clone, Slice}; + use prelude::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath}; use io::fs::PathExtensions; use time::Duration; use str; @@ -1205,6 +1207,7 @@ mod tests { #[test] #[cfg(windows)] fn env_map_keys_ci() { + use c_str::ToCStr; use super::EnvKey; let mut cmd = Command::new(""); cmd.env("path", "foo"); diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 6bd721599f3..6c8e4eea40f 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -146,7 +146,7 @@ impl StdinReader { /// ``` pub fn lock<'a>(&'a mut self) -> StdinReaderGuard<'a> { StdinReaderGuard { - inner: self.inner.lock() + inner: self.inner.lock().unwrap() } } @@ -155,7 +155,7 @@ impl StdinReader { /// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one. pub fn read_line(&mut self) -> IoResult<String> { - self.inner.lock().0.read_line() + self.inner.lock().unwrap().0.read_line() } /// Like `Buffer::read_until`. @@ -163,7 +163,7 @@ impl StdinReader { /// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one. pub fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> { - self.inner.lock().0.read_until(byte) + self.inner.lock().unwrap().0.read_until(byte) } /// Like `Buffer::read_char`. @@ -171,13 +171,13 @@ impl StdinReader { /// The read is performed atomically - concurrent read calls in other /// threads will not interleave with this one. pub fn read_char(&mut self) -> IoResult<char> { - self.inner.lock().0.read_char() + self.inner.lock().unwrap().0.read_char() } } impl Reader for StdinReader { fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { - self.inner.lock().0.read(buf) + self.inner.lock().unwrap().0.read(buf) } // We have to manually delegate all of these because the default impls call @@ -185,23 +185,23 @@ impl Reader for StdinReader { // incur the costs of repeated locking). fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> { - self.inner.lock().0.read_at_least(min, buf) + self.inner.lock().unwrap().0.read_at_least(min, buf) } fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> { - self.inner.lock().0.push_at_least(min, len, buf) + self.inner.lock().unwrap().0.push_at_least(min, len, buf) } fn read_to_end(&mut self) -> IoResult<Vec<u8>> { - self.inner.lock().0.read_to_end() + self.inner.lock().unwrap().0.read_to_end() } fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> { - self.inner.lock().0.read_le_uint_n(nbytes) + self.inner.lock().unwrap().0.read_le_uint_n(nbytes) } fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> { - self.inner.lock().0.read_be_uint_n(nbytes) + self.inner.lock().unwrap().0.read_be_uint_n(nbytes) } } diff --git a/src/libstd/io/util.rs b/src/libstd/io/util.rs index 43893ca0126..90d7c1388a1 100644 --- a/src/libstd/io/util.rs +++ b/src/libstd/io/util.rs @@ -280,7 +280,7 @@ mod test { use io; use boxed::Box; use super::*; - use prelude::*; + use prelude::{Ok, range, Vec, Buffer, Writer, Reader, ToString, AsSlice}; #[test] fn test_limit_reader_unlimited() { diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 7c8763979bb..48ff1a364e9 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -147,8 +147,10 @@ pub fn test_num<T>(ten: T, two: T) where #[cfg(test)] mod tests { - use prelude::*; - use super::*; + use prelude::{range, Some, None, Option, IteratorExt}; + use super::{from_int, from_uint, from_i32, from_i64, from_u64, from_u32}; + use super::{from_f64, from_f32, from_u16, from_i16, from_u8, from_i8, Int}; + use super::{cast, NumCast, ToPrimitive, FromPrimitive, UnsignedInt}; use i8; use i16; use i32; diff --git a/src/libstd/os.rs b/src/libstd/os.rs index ceb9a4102f6..989f44f7b8e 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -46,7 +46,8 @@ use option::Option; use option::Option::{Some, None}; use path::{Path, GenericPath, BytesContainer}; use sys; -use ptr::RawPtr; +use sys::os as os_imp; +use ptr::PtrExt; use ptr; use result::Result; use result::Result::{Err, Ok}; @@ -730,7 +731,7 @@ fn real_args() -> Vec<String> { let ptr = ptr as *const u16; let buf = slice::from_raw_buf(&ptr, len); let opt_s = String::from_utf16(sys::os::truncate_utf16_at_nul(buf)); - opt_s.expect("CommandLineToArgvW returned invalid UTF-16") + opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16") }); unsafe { @@ -1438,7 +1439,7 @@ mod tests { } fn make_rand_name() -> String { - let mut rng = rand::task_rng(); + let mut rng = rand::thread_rng(); let n = format!("TEST{}", rng.gen_ascii_chars().take(10u) .collect::<String>()); assert!(getenv(n.as_slice()).is_none()); diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index d941665f048..60f147eac9b 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -1239,7 +1239,7 @@ mod bench { extern crate test; use self::test::Bencher; use super::*; - use prelude::*; + use prelude::{Clone, GenericPath}; #[bench] fn join_home_dir(b: &mut Bencher) { diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 1d17ae987b2..879a96e8026 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -21,7 +21,7 @@ use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering}; use hash; use io::Writer; use iter::{AdditiveIterator, DoubleEndedIteratorExt, Extend}; -use iter::{Iterator, IteratorExt, Map}; +use iter::{Iterator, IteratorExt, Map, repeat}; use mem; use option::Option; use option::Option::{Some, None}; @@ -777,7 +777,7 @@ impl Path { } } } else if is_abs && comps.is_empty() { - Some(String::from_char(1, SEP)) + Some(repeat(SEP).take(1).collect()) } else { let prefix_ = s[0..prefix_len(prefix)]; let n = prefix_.len() + diff --git a/src/libstd/prelude.rs b/src/libstd/prelude.rs index d1540f98a23..fc59f06ae6c 100644 --- a/src/libstd/prelude.rs +++ b/src/libstd/prelude.rs @@ -73,7 +73,7 @@ #[doc(no_inline)] pub use option::Option; #[doc(no_inline)] pub use option::Option::{Some, None}; #[doc(no_inline)] pub use path::{GenericPath, Path, PosixPath, WindowsPath}; -#[doc(no_inline)] pub use ptr::{RawPtr, RawMutPtr}; +#[doc(no_inline)] pub use ptr::{PtrExt, MutPtrExt}; #[doc(no_inline)] pub use result::Result; #[doc(no_inline)] pub use result::Result::{Ok, Err}; #[doc(no_inline)] pub use io::{Buffer, Writer, Reader, Seek, BufferPrelude}; diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index c590c0f575e..d4f72a53aec 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -18,10 +18,10 @@ //! See the `distributions` submodule for sampling random numbers from //! distributions like normal and exponential. //! -//! # Task-local RNG +//! # Thread-local RNG //! -//! There is built-in support for a RNG associated with each task stored -//! in task-local storage. This RNG can be accessed via `task_rng`, or +//! There is built-in support for a RNG associated with each thread stored +//! in thread-local storage. This RNG can be accessed via `thread_rng`, or //! used implicitly via `random`. This RNG is normally randomly seeded //! from an operating-system source of randomness, e.g. `/dev/urandom` on //! Unix systems, and will automatically reseed itself from this source @@ -61,7 +61,7 @@ //! use std::rand; //! use std::rand::Rng; //! -//! let mut rng = rand::task_rng(); +//! let mut rng = rand::thread_rng(); //! if rng.gen() { // random bool //! println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>()) //! } @@ -97,7 +97,7 @@ //! //! fn main() { //! let between = Range::new(-1f64, 1.); -//! let mut rng = rand::task_rng(); +//! let mut rng = rand::thread_rng(); //! //! let total = 1_000_000u; //! let mut in_circle = 0u; @@ -183,7 +183,7 @@ //! // The estimation will be more accurate with more simulations //! let num_simulations = 10000u; //! -//! let mut rng = rand::task_rng(); +//! let mut rng = rand::thread_rng(); //! let random_door = Range::new(0u, 3); //! //! let (mut switch_wins, mut switch_losses) = (0u, 0u); @@ -257,7 +257,7 @@ impl StdRng { /// randomness from the operating system and use this in an /// expensive seeding operation. If one is only generating a small /// number of random numbers, or doesn't need the utmost speed for - /// generating each number, `task_rng` and/or `random` may be more + /// generating each number, `thread_rng` and/or `random` may be more /// appropriate. /// /// Reading the randomness from the OS may fail, and any error is @@ -307,28 +307,28 @@ pub fn weak_rng() -> XorShiftRng { } } -/// Controls how the task-local RNG is reseeded. -struct TaskRngReseeder; +/// Controls how the thread-local RNG is reseeded. +struct ThreadRngReseeder; -impl reseeding::Reseeder<StdRng> for TaskRngReseeder { +impl reseeding::Reseeder<StdRng> for ThreadRngReseeder { fn reseed(&mut self, rng: &mut StdRng) { *rng = match StdRng::new() { Ok(r) => r, - Err(e) => panic!("could not reseed task_rng: {}", e) + Err(e) => panic!("could not reseed thread_rng: {}", e) } } } -static TASK_RNG_RESEED_THRESHOLD: uint = 32_768; -type TaskRngInner = reseeding::ReseedingRng<StdRng, TaskRngReseeder>; +static THREAD_RNG_RESEED_THRESHOLD: uint = 32_768; +type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>; -/// The task-local RNG. -pub struct TaskRng { - rng: Rc<RefCell<TaskRngInner>>, +/// The thread-local RNG. +pub struct ThreadRng { + rng: Rc<RefCell<ThreadRngInner>>, } -/// Retrieve the lazily-initialized task-local random number +/// Retrieve the lazily-initialized thread-local random number /// generator, seeded by the system. Intended to be used in method -/// chaining style, e.g. `task_rng().gen::<int>()`. +/// chaining style, e.g. `thread_rng().gen::<int>()`. /// /// The RNG provided will reseed itself from the operating system /// after generating a certain amount of randomness. @@ -337,23 +337,23 @@ pub struct TaskRng { /// if the operating system random number generator is rigged to give /// the same sequence always. If absolute consistency is required, /// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`. -pub fn task_rng() -> TaskRng { +pub fn thread_rng() -> ThreadRng { // used to make space in TLS for a random number generator - thread_local!(static TASK_RNG_KEY: Rc<RefCell<TaskRngInner>> = { + thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = { let r = match StdRng::new() { Ok(r) => r, - Err(e) => panic!("could not initialize task_rng: {}", e) + Err(e) => panic!("could not initialize thread_rng: {}", e) }; let rng = reseeding::ReseedingRng::new(r, - TASK_RNG_RESEED_THRESHOLD, - TaskRngReseeder); + THREAD_RNG_RESEED_THRESHOLD, + ThreadRngReseeder); Rc::new(RefCell::new(rng)) }); - TaskRng { rng: TASK_RNG_KEY.with(|t| t.clone()) } + ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) } } -impl Rng for TaskRng { +impl Rng for ThreadRng { fn next_u32(&mut self) -> u32 { self.rng.borrow_mut().next_u32() } @@ -368,7 +368,7 @@ impl Rng for TaskRng { } } -/// Generates a random value using the task-local random number generator. +/// Generates a random value using the thread-local random number generator. /// /// `random()` can generate various types of random things, and so may require /// type hinting to generate the specific type you want. @@ -390,7 +390,7 @@ impl Rng for TaskRng { /// ``` #[inline] pub fn random<T: Rand>() -> T { - task_rng().gen() + thread_rng().gen() } /// Randomly sample up to `amount` elements from an iterator. @@ -398,9 +398,9 @@ pub fn random<T: Rand>() -> T { /// # Example /// /// ```rust -/// use std::rand::{task_rng, sample}; +/// use std::rand::{thread_rng, sample}; /// -/// let mut rng = task_rng(); +/// let mut rng = thread_rng(); /// let sample = sample(&mut rng, range(1i, 100), 5); /// println!("{}", sample); /// ``` @@ -420,7 +420,7 @@ pub fn sample<T, I: Iterator<T>, R: Rng>(rng: &mut R, #[cfg(test)] mod test { use prelude::*; - use super::{Rng, task_rng, random, SeedableRng, StdRng, sample}; + use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample}; use iter::order; struct ConstRng { i: u64 } @@ -453,7 +453,7 @@ mod test { #[test] fn test_gen_range() { - let mut r = task_rng(); + let mut r = thread_rng(); for _ in range(0u, 1000) { let a = r.gen_range(-3i, 42); assert!(a >= -3 && a < 42); @@ -473,20 +473,20 @@ mod test { #[test] #[should_fail] fn test_gen_range_panic_int() { - let mut r = task_rng(); + let mut r = thread_rng(); r.gen_range(5i, -2); } #[test] #[should_fail] fn test_gen_range_panic_uint() { - let mut r = task_rng(); + let mut r = thread_rng(); r.gen_range(5u, 2u); } #[test] fn test_gen_f64() { - let mut r = task_rng(); + let mut r = thread_rng(); let a = r.gen::<f64>(); let b = r.gen::<f64>(); debug!("{}", (a, b)); @@ -494,14 +494,14 @@ mod test { #[test] fn test_gen_weighted_bool() { - let mut r = task_rng(); + let mut r = thread_rng(); assert_eq!(r.gen_weighted_bool(0u), true); assert_eq!(r.gen_weighted_bool(1u), true); } #[test] fn test_gen_ascii_str() { - let mut r = task_rng(); + let mut r = thread_rng(); assert_eq!(r.gen_ascii_chars().take(0).count(), 0u); assert_eq!(r.gen_ascii_chars().take(10).count(), 10u); assert_eq!(r.gen_ascii_chars().take(16).count(), 16u); @@ -509,7 +509,7 @@ mod test { #[test] fn test_gen_vec() { - let mut r = task_rng(); + let mut r = thread_rng(); assert_eq!(r.gen_iter::<u8>().take(0).count(), 0u); assert_eq!(r.gen_iter::<u8>().take(10).count(), 10u); assert_eq!(r.gen_iter::<f64>().take(16).count(), 16u); @@ -517,7 +517,7 @@ mod test { #[test] fn test_choose() { - let mut r = task_rng(); + let mut r = thread_rng(); assert_eq!(r.choose(&[1i, 1, 1]).map(|&x|x), Some(1)); let v: &[int] = &[]; @@ -526,7 +526,7 @@ mod test { #[test] fn test_shuffle() { - let mut r = task_rng(); + let mut r = thread_rng(); let empty: &mut [int] = &mut []; r.shuffle(empty); let mut one = [1i]; @@ -545,8 +545,8 @@ mod test { } #[test] - fn test_task_rng() { - let mut r = task_rng(); + fn test_thread_rng() { + let mut r = thread_rng(); r.gen::<int>(); let mut v = [1i, 1, 1]; r.shuffle(&mut v); @@ -574,7 +574,7 @@ mod test { let min_val = 1i; let max_val = 100i; - let mut r = task_rng(); + let mut r = thread_rng(); let vals = range(min_val, max_val).collect::<Vec<int>>(); let small_sample = sample(&mut r, vals.iter(), 5); let large_sample = sample(&mut r, vals.iter(), vals.len() + 5); @@ -589,7 +589,7 @@ mod test { #[test] fn test_std_rng_seeded() { - let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>(); + let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>(); let mut ra: StdRng = SeedableRng::from_seed(s.as_slice()); let mut rb: StdRng = SeedableRng::from_seed(s.as_slice()); assert!(order::equals(ra.gen_ascii_chars().take(100), @@ -598,7 +598,7 @@ mod test { #[test] fn test_std_rng_reseed() { - let s = task_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>(); + let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>(); let mut r: StdRng = SeedableRng::from_seed(s.as_slice()); let string1 = r.gen_ascii_chars().take(100).collect::<String>(); diff --git a/src/libstd/rt/backtrace.rs b/src/libstd/rt/backtrace.rs index 775e9bb526f..3eeb0ad3968 100644 --- a/src/libstd/rt/backtrace.rs +++ b/src/libstd/rt/backtrace.rs @@ -60,19 +60,19 @@ mod test { t!("_ZN4$UP$E", "Box"); t!("_ZN8$UP$testE", "Boxtest"); t!("_ZN8$UP$test4foobE", "Boxtest::foob"); - t!("_ZN8$x20test4foobE", " test::foob"); + t!("_ZN10$u{20}test4foobE", " test::foob"); } #[test] fn demangle_many_dollars() { - t!("_ZN12test$x20test4foobE", "test test::foob"); + t!("_ZN14test$u{20}test4foobE", "test test::foob"); t!("_ZN12test$UP$test4foobE", "testBoxtest::foob"); } #[test] fn demangle_windows() { t!("ZN4testE", "test"); - t!("ZN12test$x20test4foobE", "test test::foob"); + t!("ZN14test$u{20}test4foobE", "test test::foob"); t!("ZN12test$UP$test4foobE", "testBoxtest::foob"); } } diff --git a/src/libstd/rt/mod.rs b/src/libstd/rt/mod.rs index d64336569c6..e877dd5c6aa 100644 --- a/src/libstd/rt/mod.rs +++ b/src/libstd/rt/mod.rs @@ -53,7 +53,7 @@ pub mod args; mod at_exit_imp; mod libunwind; -/// The default error code of the rust runtime if the main task panics instead +/// The default error code of the rust runtime if the main thread panics instead /// of exiting cleanly. pub const DEFAULT_ERROR_CODE: int = 101; @@ -137,9 +137,9 @@ fn lang_start(main: *const u8, argc: int, argv: *const *const u8) -> int { /// /// The procedure passed to this function will be executed as part of the /// runtime cleanup phase. For normal rust programs, this means that it will run -/// after all other tasks have exited. +/// after all other threads have exited. /// -/// The procedure is *not* executed with a local `Task` available to it, so +/// The procedure is *not* executed with a local `Thread` available to it, so /// primitives like logging, I/O, channels, spawning, etc, are *not* available. /// This is meant for "bare bones" usage to clean up runtime details, this is /// not meant as a general-purpose "let's clean everything up" function. diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index 98940a2b381..773322e4f57 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -36,7 +36,7 @@ use sys_common::stack; use rt::unwind; use rt::unwind::Unwinder; -/// State associated with Rust tasks. +/// State associated with Rust threads /// /// This structure is currently undergoing major changes, and is /// likely to be move/be merged with a `Thread` structure. @@ -50,14 +50,14 @@ pub struct Task { awoken: bool, // used to prevent spurious wakeups // This field holds the known bounds of the stack in (lo, hi) form. Not all - // native tasks necessarily know their precise bounds, hence this is + // native threads necessarily know their precise bounds, hence this is // optional. stack_bounds: (uint, uint), stack_guard: uint } -// Once a task has entered the `Armed` state it must be destroyed via `drop`, +// Once a thread has entered the `Armed` state it must be destroyed via `drop`, // and no other method. This state is used to track this transition. #[deriving(PartialEq)] enum TaskState { @@ -67,31 +67,31 @@ enum TaskState { } pub struct TaskOpts { - /// Invoke this procedure with the result of the task when it finishes. + /// Invoke this procedure with the result of the thread when it finishes. pub on_exit: Option<Thunk<Result>>, - /// A name for the task-to-be, for identification in panic messages + /// A name for the thread-to-be, for identification in panic messages pub name: Option<SendStr>, - /// The size of the stack for the spawned task + /// The size of the stack for the spawned thread pub stack_size: Option<uint>, } -/// Indicates the manner in which a task exited. +/// Indicates the manner in which a thread exited. /// -/// A task that completes without panicking is considered to exit successfully. +/// A thread that completes without panicking is considered to exit successfully. /// /// If you wish for this result's delivery to block until all -/// children tasks complete, recommend using a result future. +/// children threads complete, recommend using a result future. pub type Result = ::core::result::Result<(), Box<Any + Send>>; -/// A handle to a blocked task. Usually this means having the Box<Task> -/// pointer by ownership, but if the task is killable, a killer can steal it +/// A handle to a blocked thread. Usually this means having the Box<Task> +/// pointer by ownership, but if the thread is killable, a killer can steal it /// at any time. pub enum BlockedTask { Owned(Box<Task>), Shared(Arc<AtomicUint>), } -/// Per-task state related to task death, killing, panic, etc. +/// Per-thread state related to thread death, killing, panic, etc. pub struct Death { pub on_exit: Option<Thunk<Result>>, } @@ -101,7 +101,7 @@ pub struct BlockedTasks { } impl Task { - /// Creates a new uninitialized task. + /// Creates a new uninitialized thread. pub fn new(stack_bounds: Option<(uint, uint)>, stack_guard: Option<uint>) -> Task { Task { unwinder: Unwinder::new(), @@ -153,17 +153,17 @@ impl Task { }) } - /// Consumes ownership of a task, runs some code, and returns the task back. + /// Consumes ownership of a thread, runs some code, and returns the thread back. /// /// This function can be used as an emulated "try/catch" to interoperate /// with the rust runtime at the outermost boundary. It is not possible to /// use this function in a nested fashion (a try/catch inside of another /// try/catch). Invoking this function is quite cheap. /// - /// If the closure `f` succeeds, then the returned task can be used again + /// If the closure `f` succeeds, then the returned thread can be used again /// for another invocation of `run`. If the closure `f` panics then `self` /// will be internally destroyed along with all of the other associated - /// resources of this task. The `on_exit` callback is invoked with the + /// resources of this thread. The `on_exit` callback is invoked with the /// cause of panic (not returned here). This can be discovered by querying /// `is_destroyed()`. /// @@ -172,30 +172,30 @@ impl Task { /// guaranteed to return if it panicks. Care should be taken to ensure that /// stack references made by `f` are handled appropriately. /// - /// It is invalid to call this function with a task that has been previously + /// It is invalid to call this function with a thread that has been previously /// destroyed via a failed call to `run`. pub fn run(mut self: Box<Task>, f: ||) -> Box<Task> { - assert!(!self.is_destroyed(), "cannot re-use a destroyed task"); + assert!(!self.is_destroyed(), "cannot re-use a destroyed thread"); // First, make sure that no one else is in TLS. This does not allow // recursive invocations of run(). If there's no one else, then // relinquish ownership of ourselves back into TLS. if Local::exists(None::<Task>) { - panic!("cannot run a task recursively inside another"); + panic!("cannot run a thread recursively inside another"); } self.state = Armed; Local::put(self); // There are two primary reasons that general try/catch is unsafe. The // first is that we do not support nested try/catch. The above check for - // an existing task in TLS is sufficient for this invariant to be + // an existing thread in TLS is sufficient for this invariant to be // upheld. The second is that unwinding while unwinding is not defined. - // We take care of that by having an 'unwinding' flag in the task + // We take care of that by having an 'unwinding' flag in the thread // itself. For these reasons, this unsafety should be ok. let result = unsafe { unwind::try(f) }; - // After running the closure given return the task back out if it ran - // successfully, or clean up the task if it panicked. + // After running the closure given return the thread back out if it ran + // successfully, or clean up the thread if it panicked. let task: Box<Task> = Local::take(); match result { Ok(()) => task, @@ -203,13 +203,13 @@ impl Task { } } - /// Destroy all associated resources of this task. + /// Destroy all associated resources of this thread. /// - /// This function will perform any necessary clean up to prepare the task + /// This function will perform any necessary clean up to prepare the thread /// for destruction. It is required that this is called before a `Task` /// falls out of scope. /// - /// The returned task cannot be used for running any more code, but it may + /// The returned thread cannot be used for running any more code, but it may /// be used to extract the runtime as necessary. pub fn destroy(self: Box<Task>) -> Box<Task> { if self.is_destroyed() { @@ -219,14 +219,14 @@ impl Task { } } - /// Cleans up a task, processing the result of the task as appropriate. + /// Cleans up a thread, processing the result of the thread as appropriate. /// - /// This function consumes ownership of the task, deallocating it once it's + /// This function consumes ownership of the thread, deallocating it once it's /// done being processed. It is assumed that TLD and the local heap have /// already been destroyed and/or annihilated. fn cleanup(mut self: Box<Task>, result: Result) -> Box<Task> { // After taking care of the data above, we need to transmit the result - // of this task. + // of this thread. let what_to_do = self.death.on_exit.take(); Local::put(self); @@ -235,15 +235,15 @@ impl Task { // if this panics, this will also likely abort the runtime. // // This closure is currently limited to a channel send via the - // standard library's task interface, but this needs + // standard library's thread interface, but this needs // reconsideration to whether it's a reasonable thing to let a - // task to do or not. + // thread to do or not. match what_to_do { Some(f) => { f.invoke(result) } None => { drop(result) } } - // Now that we're done, we remove the task from TLS and flag it for + // Now that we're done, we remove the thread from TLS and flag it for // destruction. let mut task: Box<Task> = Local::take(); task.state = Destroyed; @@ -253,7 +253,7 @@ impl Task { /// Queries whether this can be destroyed or not. pub fn is_destroyed(&self) -> bool { self.state == Destroyed } - /// Deschedules the current task, invoking `f` `amt` times. It is not + /// Deschedules the current thread, invoking `f` `amt` times. It is not /// recommended to use this function directly, but rather communication /// primitives in `std::comm` should be used. // @@ -262,31 +262,31 @@ impl Task { // shared state. Additionally, all of the violations are protected with a // mutex, so in theory there are no races. // - // The first thing we need to do is to get a pointer to the task's internal - // mutex. This address will not be changing (because the task is allocated - // on the heap). We must have this handle separately because the task will + // The first thing we need to do is to get a pointer to the thread's internal + // mutex. This address will not be changing (because the thread is allocated + // on the heap). We must have this handle separately because the thread will // have its ownership transferred to the given closure. We're guaranteed, // however, that this memory will remain valid because *this* is the current - // task's execution thread. + // thread's execution thread. // - // The next weird part is where ownership of the task actually goes. We + // The next weird part is where ownership of the thread actually goes. We // relinquish it to the `f` blocking function, but upon returning this - // function needs to replace the task back in TLS. There is no communication - // from the wakeup thread back to this thread about the task pointer, and - // there's really no need to. In order to get around this, we cast the task + // function needs to replace the thread back in TLS. There is no communication + // from the wakeup thread back to this thread about the thread pointer, and + // there's really no need to. In order to get around this, we cast the thread // to a `uint` which is then used at the end of this function to cast back // to a `Box<Task>` object. Naturally, this looks like it violates // ownership semantics in that there may be two `Box<Task>` objects. // // The fun part is that the wakeup half of this implementation knows to - // "forget" the task on the other end. This means that the awakening half of + // "forget" the thread on the other end. This means that the awakening half of // things silently relinquishes ownership back to this thread, but not in a - // way that the compiler can understand. The task's memory is always valid - // for both tasks because these operations are all done inside of a mutex. + // way that the compiler can understand. The thread's memory is always valid + // for both threads because these operations are all done inside of a mutex. // // You'll also find that if blocking fails (the `f` function hands the // BlockedTask back to us), we will `mem::forget` the handles. The - // reasoning for this is the same logic as above in that the task silently + // reasoning for this is the same logic as above in that the thread silently // transfers ownership via the `uint`, not through normal compiler // semantics. // @@ -319,11 +319,11 @@ impl Task { let guard = (*me).lock.lock(); (*me).awoken = false; - // Apply the given closure to all of the "selectable tasks", + // Apply the given closure to all of the "selectable threads", // bailing on the first one that produces an error. Note that // care must be taken such that when an error is occurred, we - // may not own the task, so we may still have to wait for the - // task to become available. In other words, if task.wake() + // may not own the thread, so we may still have to wait for the + // thread to become available. In other words, if thread.wake() // returns `None`, then someone else has ownership and we must // wait for their signal. match iter.map(f).filter_map(|a| a.err()).next() { @@ -342,15 +342,15 @@ impl Task { guard.wait(); } } - // put the task back in TLS, and everything is as it once was. + // put the thread back in TLS, and everything is as it once was. Local::put(mem::transmute(me)); } } - /// Wakes up a previously blocked task. This function can only be - /// called on tasks that were previously blocked in `deschedule`. + /// Wakes up a previously blocked thread. This function can only be + /// called on threads that were previously blocked in `deschedule`. // - // See the comments on `deschedule` for why the task is forgotten here, and + // See the comments on `deschedule` for why the thread is forgotten here, and // why it's valid to do so. pub fn reawaken(mut self: Box<Task>) { unsafe { @@ -362,21 +362,21 @@ impl Task { } } - /// Yields control of this task to another task. This function will + /// Yields control of this thread to another thread. This function will /// eventually return, but possibly not immediately. This is used as an - /// opportunity to allow other tasks a chance to run. + /// opportunity to allow other threads a chance to run. pub fn yield_now() { Thread::yield_now(); } - /// Returns the stack bounds for this task in (lo, hi) format. The stack - /// bounds may not be known for all tasks, so the return value may be + /// Returns the stack bounds for this thread in (lo, hi) format. The stack + /// bounds may not be known for all threads, so the return value may be /// `None`. pub fn stack_bounds(&self) -> (uint, uint) { self.stack_bounds } - /// Returns the stack guard for this task, if known. + /// Returns the stack guard for this thread, if known. pub fn stack_guard(&self) -> Option<uint> { if self.stack_guard != 0 { Some(self.stack_guard) @@ -385,9 +385,9 @@ impl Task { } } - /// Consume this task, flagging it as a candidate for destruction. + /// Consume this thread, flagging it as a candidate for destruction. /// - /// This function is required to be invoked to destroy a task. A task + /// This function is required to be invoked to destroy a thread. A thread /// destroyed through a normal drop will abort. pub fn drop(mut self) { self.state = Destroyed; @@ -396,7 +396,7 @@ impl Task { impl Drop for Task { fn drop(&mut self) { - rtdebug!("called drop for a task: {}", self as *mut Task as uint); + rtdebug!("called drop for a thread: {}", self as *mut Task as uint); rtassert!(self.state != Armed); } } @@ -414,7 +414,7 @@ impl Iterator<BlockedTask> for BlockedTasks { } impl BlockedTask { - /// Returns Some if the task was successfully woken; None if already killed. + /// Returns Some if the thread was successfully woken; None if already killed. pub fn wake(self) -> Option<Box<Task>> { match self { Owned(task) => Some(task), @@ -427,7 +427,7 @@ impl BlockedTask { } } - /// Reawakens this task if ownership is acquired. If finer-grained control + /// Reawakens this thread if ownership is acquired. If finer-grained control /// is desired, use `wake` instead. pub fn reawaken(self) { self.wake().map(|t| t.reawaken()); @@ -438,12 +438,12 @@ impl BlockedTask { #[cfg(not(test))] pub fn trash(self) { } #[cfg(test)] pub fn trash(self) { assert!(self.wake().is_none()); } - /// Create a blocked task, unless the task was already killed. + /// Create a blocked thread, unless the thread was already killed. pub fn block(task: Box<Task>) -> BlockedTask { Owned(task) } - /// Converts one blocked task handle to a list of many handles to the same. + /// Converts one blocked thread handle to a list of many handles to the same. pub fn make_selectable(self, num_handles: uint) -> Take<BlockedTasks> { let arc = match self { Owned(task) => { @@ -543,7 +543,7 @@ mod test { drop(Task::new(None, None)); } - // Task blocking tests + // Thread blocking tests #[test] fn block_and_wake() { diff --git a/src/libstd/rt/unwind.rs b/src/libstd/rt/unwind.rs index 261a8335173..9b57dcc9e18 100644 --- a/src/libstd/rt/unwind.rs +++ b/src/libstd/rt/unwind.rs @@ -79,7 +79,7 @@ struct Exception { pub type Callback = fn(msg: &(Any + Send), file: &'static str, line: uint); -// Variables used for invoking callbacks when a task starts to unwind. +// Variables used for invoking callbacks when a thread starts to unwind. // // For more information, see below. const MAX_CALLBACKS: uint = 16; @@ -106,14 +106,14 @@ thread_local! { static PANICKING: Cell<bool> = Cell::new(false) } /// /// * This is not safe to call in a nested fashion. The unwinding /// interface for Rust is designed to have at most one try/catch block per -/// task, not multiple. No runtime checking is currently performed to uphold +/// thread, not multiple. No runtime checking is currently performed to uphold /// this invariant, so this function is not safe. A nested try/catch block /// may result in corruption of the outer try/catch block's state, especially -/// if this is used within a task itself. +/// if this is used within a thread itself. /// -/// * It is not sound to trigger unwinding while already unwinding. Rust tasks +/// * It is not sound to trigger unwinding while already unwinding. Rust threads /// have runtime checks in place to ensure this invariant, but it is not -/// guaranteed that a rust task is in place when invoking this function. +/// guaranteed that a rust thread is in place when invoking this function. /// Unwinding twice can lead to resource leaks where some destructors are not /// run. pub unsafe fn try<F: FnOnce()>(f: F) -> Result<(), Box<Any + Send>> { @@ -203,7 +203,7 @@ fn rust_exception_class() -> uw::_Unwind_Exception_Class { // _URC_INSTALL_CONTEXT (i.e. "invoke cleanup code") in cleanup phase. // // This is pretty close to Rust's exception handling approach, except that Rust -// does have a single "catch-all" handler at the bottom of each task's stack. +// does have a single "catch-all" handler at the bottom of each thread's stack. // So we have two versions of the personality routine: // - rust_eh_personality, used by all cleanup landing pads, which never catches, // so the behavior of __gcc_personality_v0 is perfectly adequate there, and @@ -570,7 +570,7 @@ pub fn begin_unwind<M: Any + Send>(msg: M, file_line: &(&'static str, uint)) -> // Currently this means that panic!() on OOM will invoke this code path, // but then again we're not really ready for panic on OOM anyway. If // we do start doing this, then we should propagate this allocation to - // be performed in the parent of this task instead of the task that's + // be performed in the parent of this thread instead of the thread that's // panicking. // see below for why we do the `Any` coercion here. @@ -593,7 +593,7 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> static INIT: Once = ONCE_INIT; INIT.doit(|| unsafe { register(failure::on_fail); }); - // First, invoke call the user-defined callbacks triggered on task panic. + // First, invoke call the user-defined callbacks triggered on thread panic. // // By the time that we see a callback has been registered (by reading // MAX_CALLBACKS), the actual callback itself may have not been stored yet, @@ -621,7 +621,7 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> // If a thread panics while it's already unwinding then we // have limited options. Currently our preference is to // just abort. In the future we may consider resuming - // unwinding or otherwise exiting the task cleanly. + // unwinding or otherwise exiting the thread cleanly. rterrln!("thread panicked while panicking. aborting."); unsafe { intrinsics::abort() } } @@ -629,10 +629,10 @@ fn begin_unwind_inner(msg: Box<Any + Send>, file_line: &(&'static str, uint)) -> rust_panic(msg); } -/// Register a callback to be invoked when a task unwinds. +/// Register a callback to be invoked when a thread unwinds. /// /// This is an unsafe and experimental API which allows for an arbitrary -/// callback to be invoked when a task panics. This callback is invoked on both +/// callback to be invoked when a thread panics. This callback is invoked on both /// the initial unwinding and a double unwinding if one occurs. Additionally, /// the local `Task` will be in place for the duration of the callback, and /// the callback must ensure that it remains in place once the callback returns. diff --git a/src/libstd/sync/atomic.rs b/src/libstd/sync/atomic.rs index 26778ef70b3..bdf947438f3 100644 --- a/src/libstd/sync/atomic.rs +++ b/src/libstd/sync/atomic.rs @@ -180,7 +180,7 @@ impl<T: Send> Drop for AtomicOption<T> { #[cfg(test)] mod test { - use prelude::*; + use prelude::{Some, None}; use super::*; #[test] diff --git a/src/libstd/sync/barrier.rs b/src/libstd/sync/barrier.rs index 6cdb199819a..4091f0df395 100644 --- a/src/libstd/sync/barrier.rs +++ b/src/libstd/sync/barrier.rs @@ -69,7 +69,7 @@ impl Barrier { /// Barriers are re-usable after all threads have rendezvoused once, and can /// be used continuously. pub fn wait(&self) { - let mut lock = self.lock.lock(); + let mut lock = self.lock.lock().unwrap(); let local_gen = lock.generation_id; lock.count += 1; if lock.count < self.num_threads { @@ -77,7 +77,7 @@ impl Barrier { // http://en.wikipedia.org/wiki/Spurious_wakeup while local_gen == lock.generation_id && lock.count < self.num_threads { - self.cvar.wait(&lock); + lock = self.cvar.wait(lock).unwrap(); } } else { lock.count = 0; diff --git a/src/libstd/sync/condvar.rs b/src/libstd/sync/condvar.rs index f1940bfd829..15faf5be258 100644 --- a/src/libstd/sync/condvar.rs +++ b/src/libstd/sync/condvar.rs @@ -11,10 +11,11 @@ use prelude::*; use sync::atomic::{mod, AtomicUint}; -use sync::{mutex, StaticMutexGuard}; +use sync::poison::{mod, LockResult}; use sys_common::condvar as sys; use sys_common::mutex as sys_mutex; use time::Duration; +use sync::{mutex, MutexGuard}; /// A Condition Variable /// @@ -44,18 +45,19 @@ use time::Duration; /// // Inside of our lock, spawn a new thread, and then wait for it to start /// Thread::spawn(move|| { /// let &(ref lock, ref cvar) = &*pair2; -/// let mut started = lock.lock(); +/// let mut started = lock.lock().unwrap(); /// *started = true; /// cvar.notify_one(); /// }).detach(); /// /// // wait for the thread to start up /// let &(ref lock, ref cvar) = &*pair; -/// let started = lock.lock(); +/// let mut started = lock.lock().unwrap(); /// while !*started { -/// cvar.wait(&started); +/// started = cvar.wait(started).unwrap(); /// } /// ``` +#[stable] pub struct Condvar { inner: Box<StaticCondvar> } unsafe impl Send for Condvar {} @@ -73,6 +75,7 @@ unsafe impl Sync for Condvar {} /// /// static CVAR: StaticCondvar = CONDVAR_INIT; /// ``` +#[unstable = "may be merged with Condvar in the future"] pub struct StaticCondvar { inner: sys::Condvar, mutex: AtomicUint, @@ -82,24 +85,16 @@ unsafe impl Send for StaticCondvar {} unsafe impl Sync for StaticCondvar {} /// Constant initializer for a statically allocated condition variable. +#[unstable = "may be merged with Condvar in the future"] pub const CONDVAR_INIT: StaticCondvar = StaticCondvar { inner: sys::CONDVAR_INIT, mutex: atomic::INIT_ATOMIC_UINT, }; -/// A trait for vaules which can be passed to the waiting methods of condition -/// variables. This is implemented by the mutex guards in this module. -/// -/// Note that this trait should likely not be implemented manually unless you -/// really know what you're doing. -pub trait AsMutexGuard { - #[allow(missing_docs)] - unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard; -} - impl Condvar { /// Creates a new condition variable which is ready to be waited on and /// notified. + #[stable] pub fn new() -> Condvar { Condvar { inner: box StaticCondvar { @@ -113,8 +108,8 @@ impl Condvar { /// notification. /// /// This function will atomically unlock the mutex specified (represented by - /// `guard`) and block the current thread. This means that any calls to - /// `notify_*()` which happen logically after the mutex is unlocked are + /// `mutex_guard`) and block the current thread. This means that any calls + /// to `notify_*()` which happen logically after the mutex is unlocked are /// candidates to wake this thread up. When this function call returns, the /// lock specified will have been re-acquired. /// @@ -123,16 +118,24 @@ impl Condvar { /// the predicate must always be checked each time this function returns to /// protect against spurious wakeups. /// + /// # Failure + /// + /// This function will return an error if the mutex being waited on is + /// poisoned when this thread re-acquires the lock. For more information, + /// see information about poisoning on the Mutex type. + /// /// # Panics /// /// This function will `panic!()` if it is used with more than one mutex /// over time. Each condition variable is dynamically bound to exactly one /// mutex to ensure defined behavior across platforms. If this functionality /// is not desired, then unsafe primitives in `sys` are provided. - pub fn wait<T: AsMutexGuard>(&self, mutex_guard: &T) { + #[stable] + pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) + -> LockResult<MutexGuard<'a, T>> { unsafe { let me: &'static Condvar = &*(self as *const _); - me.inner.wait(mutex_guard) + me.inner.wait(guard) } } @@ -156,11 +159,11 @@ impl Condvar { // provide. There are also additional concerns about the unix-specific // implementation which may need to be addressed. #[allow(dead_code)] - fn wait_timeout<T: AsMutexGuard>(&self, mutex_guard: &T, - dur: Duration) -> bool { + fn wait_timeout<'a, T>(&self, guard: MutexGuard<'a, T>, dur: Duration) + -> LockResult<(MutexGuard<'a, T>, bool)> { unsafe { let me: &'static Condvar = &*(self as *const _); - me.inner.wait_timeout(mutex_guard, dur) + me.inner.wait_timeout(guard, dur) } } @@ -171,6 +174,7 @@ impl Condvar { /// `notify_one` are not buffered in any way. /// /// To wake up all threads, see `notify_one()`. + #[stable] pub fn notify_one(&self) { unsafe { self.inner.inner.notify_one() } } /// Wake up all blocked threads on this condvar. @@ -180,6 +184,7 @@ impl Condvar { /// way. /// /// To wake up only one thread, see `notify_one()`. + #[stable] pub fn notify_all(&self) { unsafe { self.inner.inner.notify_all() } } } @@ -194,13 +199,19 @@ impl StaticCondvar { /// notification. /// /// See `Condvar::wait`. - pub fn wait<T: AsMutexGuard>(&'static self, mutex_guard: &T) { - unsafe { - let lock = mutex_guard.as_mutex_guard(); - let sys = mutex::guard_lock(lock); - self.verify(sys); - self.inner.wait(sys); - (*mutex::guard_poison(lock)).check("mutex"); + #[unstable = "may be merged with Condvar in the future"] + pub fn wait<'a, T>(&'static self, guard: MutexGuard<'a, T>) + -> LockResult<MutexGuard<'a, T>> { + let poisoned = unsafe { + let lock = mutex::guard_lock(&guard); + self.verify(lock); + self.inner.wait(lock); + mutex::guard_poison(&guard).get() + }; + if poisoned { + Err(poison::new_poison_error(guard)) + } else { + Ok(guard) } } @@ -209,26 +220,31 @@ impl StaticCondvar { /// /// See `Condvar::wait_timeout`. #[allow(dead_code)] // may want to stabilize this later, see wait_timeout above - fn wait_timeout<T: AsMutexGuard>(&'static self, mutex_guard: &T, - dur: Duration) -> bool { - unsafe { - let lock = mutex_guard.as_mutex_guard(); - let sys = mutex::guard_lock(lock); - self.verify(sys); - let ret = self.inner.wait_timeout(sys, dur); - (*mutex::guard_poison(lock)).check("mutex"); - return ret; + fn wait_timeout<'a, T>(&'static self, guard: MutexGuard<'a, T>, dur: Duration) + -> LockResult<(MutexGuard<'a, T>, bool)> { + let (poisoned, success) = unsafe { + let lock = mutex::guard_lock(&guard); + self.verify(lock); + let success = self.inner.wait_timeout(lock, dur); + (mutex::guard_poison(&guard).get(), success) + }; + if poisoned { + Err(poison::new_poison_error((guard, success))) + } else { + Ok((guard, success)) } } /// Wake up one blocked thread on this condvar. /// /// See `Condvar::notify_one`. + #[unstable = "may be merged with Condvar in the future"] pub fn notify_one(&'static self) { unsafe { self.inner.notify_one() } } /// Wake up all blocked threads on this condvar. /// /// See `Condvar::notify_all`. + #[unstable = "may be merged with Condvar in the future"] pub fn notify_all(&'static self) { unsafe { self.inner.notify_all() } } /// Deallocate all resources associated with this static condvar. @@ -237,6 +253,7 @@ impl StaticCondvar { /// active users of the condvar, and this also doesn't prevent any future /// users of the condvar. This method is required to be called to not leak /// memory on all platforms. + #[unstable = "may be merged with Condvar in the future"] pub unsafe fn destroy(&'static self) { self.inner.destroy() } @@ -288,12 +305,12 @@ mod tests { static C: StaticCondvar = CONDVAR_INIT; static M: StaticMutex = MUTEX_INIT; - let g = M.lock(); + let g = M.lock().unwrap(); spawn(move|| { - let _g = M.lock(); + let _g = M.lock().unwrap(); C.notify_one(); }); - C.wait(&g); + let g = C.wait(g).unwrap(); drop(g); unsafe { C.destroy(); M.destroy(); } } @@ -309,13 +326,13 @@ mod tests { let tx = tx.clone(); spawn(move|| { let &(ref lock, ref cond) = &*data; - let mut cnt = lock.lock(); + let mut cnt = lock.lock().unwrap(); *cnt += 1; if *cnt == N { tx.send(()); } while *cnt != 0 { - cond.wait(&cnt); + cnt = cond.wait(cnt).unwrap(); } tx.send(()); }); @@ -324,7 +341,7 @@ mod tests { let &(ref lock, ref cond) = &*data; rx.recv(); - let mut cnt = lock.lock(); + let mut cnt = lock.lock().unwrap(); *cnt = 0; cond.notify_all(); drop(cnt); @@ -339,13 +356,15 @@ mod tests { static C: StaticCondvar = CONDVAR_INIT; static M: StaticMutex = MUTEX_INIT; - let g = M.lock(); - assert!(!C.wait_timeout(&g, Duration::nanoseconds(1000))); + let g = M.lock().unwrap(); + let (g, success) = C.wait_timeout(g, Duration::nanoseconds(1000)).unwrap(); + assert!(!success); spawn(move|| { - let _g = M.lock(); + let _g = M.lock().unwrap(); C.notify_one(); }); - assert!(C.wait_timeout(&g, Duration::days(1))); + let (g, success) = C.wait_timeout(g, Duration::days(1)).unwrap(); + assert!(success); drop(g); unsafe { C.destroy(); M.destroy(); } } @@ -357,15 +376,15 @@ mod tests { static M2: StaticMutex = MUTEX_INIT; static C: StaticCondvar = CONDVAR_INIT; - let g = M1.lock(); + let mut g = M1.lock().unwrap(); spawn(move|| { - let _g = M1.lock(); + let _g = M1.lock().unwrap(); C.notify_one(); }); - C.wait(&g); + g = C.wait(g).unwrap(); drop(g); - C.wait(&M2.lock()); + C.wait(M2.lock().unwrap()).unwrap(); } } diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 7605a6a96a0..092acc7ff25 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -19,14 +19,15 @@ pub use alloc::arc::{Arc, Weak}; -pub use self::mutex::{Mutex, MutexGuard, StaticMutex, StaticMutexGuard, MUTEX_INIT}; +pub use self::mutex::{Mutex, MutexGuard, StaticMutex}; +pub use self::mutex::MUTEX_INIT; pub use self::rwlock::{RWLock, StaticRWLock, RWLOCK_INIT}; pub use self::rwlock::{RWLockReadGuard, RWLockWriteGuard}; -pub use self::rwlock::{StaticRWLockReadGuard, StaticRWLockWriteGuard}; -pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT, AsMutexGuard}; +pub use self::condvar::{Condvar, StaticCondvar, CONDVAR_INIT}; pub use self::once::{Once, ONCE_INIT}; pub use self::semaphore::{Semaphore, SemaphoreGuard}; pub use self::barrier::Barrier; +pub use self::poison::{PoisonError, TryLockError, TryLockResult, LockResult}; pub use self::future::Future; pub use self::task_pool::TaskPool; diff --git a/src/libstd/sync/mutex.rs b/src/libstd/sync/mutex.rs index 4d2fbfc4055..52004bb4a8f 100644 --- a/src/libstd/sync/mutex.rs +++ b/src/libstd/sync/mutex.rs @@ -12,7 +12,7 @@ use prelude::*; use cell::UnsafeCell; use kinds::marker; -use sync::{poison, AsMutexGuard}; +use sync::poison::{mod, TryLockError, TryLockResult, LockResult}; use sys_common::mutex as sys; /// A mutual exclusion primitive useful for protecting shared data @@ -26,12 +26,23 @@ use sys_common::mutex as sys; /// /// # Poisoning /// -/// In order to prevent access to otherwise invalid data, each mutex will -/// propagate any panics which occur while the lock is held. Once a thread has -/// panicked while holding the lock, then all other threads will immediately -/// panic as well once they hold the lock. +/// The mutexes in this module implement a strategy called "poisoning" where a +/// mutex is considered poisoned whenever a thread panics while holding the +/// lock. Once a mutex is poisoned, all other tasks are unable to access the +/// data by default as it is likely tainted (some invariant is not being +/// upheld). /// -/// # Example +/// For a mutex, this means that the `lock` and `try_lock` methods return a +/// `Result` which indicates whether a mutex has been poisoned or not. Most +/// usage of a mutex will simply `unwrap()` these results, propagating panics +/// among threads to ensure that a possibly invalid invariant is not witnessed. +/// +/// A poisoned mutex, however, does not prevent all access to the underlying +/// data. The `PoisonError` type has an `into_guard` method which will return +/// the guard that would have otherwise been returned on a successful lock. This +/// allows access to the data, despite the lock being poisoned. +/// +/// # Examples /// /// ```rust /// use std::sync::{Arc, Mutex}; @@ -48,11 +59,14 @@ use sys_common::mutex as sys; /// let (tx, rx) = channel(); /// for _ in range(0u, 10) { /// let (data, tx) = (data.clone(), tx.clone()); -/// Thread::spawn(move|| { +/// Thread::spawn(move || { /// // The shared static can only be accessed once the lock is held. /// // Our non-atomic increment is safe because we're the only thread /// // which can access the shared state when the lock is held. -/// let mut data = data.lock(); +/// // +/// // We unwrap() the return value to assert that we are not expecting +/// // tasks to ever fail while holding the lock. +/// let mut data = data.lock().unwrap(); /// *data += 1; /// if *data == N { /// tx.send(()); @@ -63,6 +77,36 @@ use sys_common::mutex as sys; /// /// rx.recv(); /// ``` +/// +/// To recover from a poisoned mutex: +/// +/// ```rust +/// use std::sync::{Arc, Mutex}; +/// use std::thread::Thread; +/// +/// let lock = Arc::new(Mutex::new(0u)); +/// let lock2 = lock.clone(); +/// +/// let _ = Thread::spawn(move || -> () { +/// // This thread will acquire the mutex first, unwrapping the result of +/// // `lock` because the lock has not been poisoned. +/// let _lock = lock2.lock().unwrap(); +/// +/// // This panic while holding the lock (`_guard` is in scope) will poison +/// // the mutex. +/// panic!(); +/// }).join(); +/// +/// // The lock is poisoned by this point, but the returned result can be +/// // pattern matched on to return the underlying guard on both branches. +/// let mut guard = match lock.lock() { +/// Ok(guard) => guard, +/// Err(poisoned) => poisoned.into_guard(), +/// }; +/// +/// *guard += 1; +/// ``` +#[stable] pub struct Mutex<T> { // Note that this static mutex is in a *box*, not inlined into the struct // itself. Once a native mutex has been used once, its address can never @@ -93,14 +137,15 @@ unsafe impl<T:Send> Sync for Mutex<T> { } /// static LOCK: StaticMutex = MUTEX_INIT; /// /// { -/// let _g = LOCK.lock(); +/// let _g = LOCK.lock().unwrap(); /// // do some productive work /// } /// // lock is unlocked here. /// ``` +#[unstable = "may be merged with Mutex in the future"] pub struct StaticMutex { lock: sys::Mutex, - poison: UnsafeCell<poison::Flag>, + poison: poison::Flag, } unsafe impl Sync for StaticMutex {} @@ -111,31 +156,27 @@ unsafe impl Sync for StaticMutex {} /// The data protected by the mutex can be access through this guard via its /// Deref and DerefMut implementations #[must_use] +#[stable] pub struct MutexGuard<'a, T: 'a> { // funny underscores due to how Deref/DerefMut currently work (they // disregard field privacy). - __lock: &'a Mutex<T>, - __guard: StaticMutexGuard, -} - -/// An RAII implementation of a "scoped lock" of a static mutex. When this -/// structure is dropped (falls out of scope), the lock will be unlocked. -#[must_use] -pub struct StaticMutexGuard { - lock: &'static sys::Mutex, - marker: marker::NoSend, - poison: poison::Guard<'static>, + __lock: &'a StaticMutex, + __data: &'a UnsafeCell<T>, + __poison: poison::Guard, + __marker: marker::NoSend, } /// Static initialization of a mutex. This constant can be used to initialize /// other mutex constants. +#[unstable = "may be merged with Mutex in the future"] pub const MUTEX_INIT: StaticMutex = StaticMutex { lock: sys::MUTEX_INIT, - poison: UnsafeCell { value: poison::Flag { failed: false } }, + poison: poison::FLAG_INIT, }; impl<T: Send> Mutex<T> { /// Creates a new mutex in an unlocked state ready for use. + #[stable] pub fn new(t: T) -> Mutex<T> { Mutex { inner: box MUTEX_INIT, @@ -150,15 +191,14 @@ impl<T: Send> Mutex<T> { /// 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. /// - /// # Panics + /// # Failure /// /// If another user of this mutex panicked while holding the mutex, then - /// this call will immediately panic once the mutex is acquired. - pub fn lock(&self) -> MutexGuard<T> { - unsafe { - let lock: &'static StaticMutex = &*(&*self.inner as *const _); - MutexGuard::new(self, lock.lock()) - } + /// this call will return an error once the mutex is acquired. + #[stable] + pub fn lock(&self) -> LockResult<MutexGuard<T>> { + unsafe { self.inner.lock.lock() } + MutexGuard::new(&*self.inner, &self.data) } /// Attempts to acquire this lock. @@ -169,17 +209,17 @@ impl<T: Send> Mutex<T> { /// /// This function does not block. /// - /// # Panics + /// # Failure /// /// If another user of this mutex panicked while holding the mutex, then - /// this call will immediately panic if the mutex would otherwise be + /// this call will return failure if the mutex would otherwise be /// acquired. - pub fn try_lock(&self) -> Option<MutexGuard<T>> { - unsafe { - let lock: &'static StaticMutex = &*(&*self.inner as *const _); - lock.try_lock().map(|guard| { - MutexGuard::new(self, guard) - }) + #[stable] + pub fn try_lock(&self) -> TryLockResult<MutexGuard<T>> { + if unsafe { self.inner.lock.try_lock() } { + Ok(try!(MutexGuard::new(&*self.inner, &self.data))) + } else { + Err(TryLockError::WouldBlock) } } } @@ -194,19 +234,27 @@ impl<T: Send> Drop for Mutex<T> { } } +struct Dummy(UnsafeCell<()>); +unsafe impl Sync for Dummy {} +static DUMMY: Dummy = Dummy(UnsafeCell { value: () }); + impl StaticMutex { /// Acquires this lock, see `Mutex::lock` - pub fn lock(&'static self) -> StaticMutexGuard { + #[inline] + #[unstable = "may be merged with Mutex in the future"] + pub fn lock(&'static self) -> LockResult<MutexGuard<()>> { unsafe { self.lock.lock() } - StaticMutexGuard::new(self) + MutexGuard::new(self, &DUMMY.0) } /// Attempts to grab this lock, see `Mutex::try_lock` - pub fn try_lock(&'static self) -> Option<StaticMutexGuard> { + #[inline] + #[unstable = "may be merged with Mutex in the future"] + pub fn try_lock(&'static self) -> TryLockResult<MutexGuard<()>> { if unsafe { self.lock.try_lock() } { - Some(StaticMutexGuard::new(self)) + Ok(try!(MutexGuard::new(self, &DUMMY.0))) } else { - None + Err(TryLockError::WouldBlock) } } @@ -220,61 +268,54 @@ 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. + #[unstable = "may be merged with Mutex in the future"] pub unsafe fn destroy(&'static self) { self.lock.destroy() } } impl<'mutex, T> MutexGuard<'mutex, T> { - fn new(lock: &Mutex<T>, guard: StaticMutexGuard) -> MutexGuard<T> { - MutexGuard { __lock: lock, __guard: guard } + fn new(lock: &'mutex StaticMutex, data: &'mutex UnsafeCell<T>) + -> LockResult<MutexGuard<'mutex, T>> { + poison::map_result(lock.poison.borrow(), |guard| { + MutexGuard { + __lock: lock, + __data: data, + __poison: guard, + __marker: marker::NoSend, + } + }) } } -impl<'mutex, T> AsMutexGuard for MutexGuard<'mutex, T> { - unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { &self.__guard } -} - impl<'mutex, T> Deref<T> for MutexGuard<'mutex, T> { - fn deref<'a>(&'a self) -> &'a T { unsafe { &*self.__lock.data.get() } } + fn deref<'a>(&'a self) -> &'a T { + unsafe { &*self.__data.get() } + } } impl<'mutex, T> DerefMut<T> for MutexGuard<'mutex, T> { fn deref_mut<'a>(&'a mut self) -> &'a mut T { - unsafe { &mut *self.__lock.data.get() } + unsafe { &mut *self.__data.get() } } } -impl StaticMutexGuard { - fn new(lock: &'static StaticMutex) -> StaticMutexGuard { +#[unsafe_destructor] +impl<'a, T> Drop for MutexGuard<'a, T> { + #[inline] + fn drop(&mut self) { unsafe { - let guard = StaticMutexGuard { - lock: &lock.lock, - marker: marker::NoSend, - poison: (*lock.poison.get()).borrow(), - }; - guard.poison.check("mutex"); - return guard; + self.__lock.poison.done(&self.__poison); + self.__lock.lock.unlock(); } } } -pub fn guard_lock(guard: &StaticMutexGuard) -> &sys::Mutex { guard.lock } -pub fn guard_poison(guard: &StaticMutexGuard) -> &poison::Guard { - &guard.poison +pub fn guard_lock<'a, T>(guard: &MutexGuard<'a, T>) -> &'a sys::Mutex { + &guard.__lock.lock } -impl AsMutexGuard for StaticMutexGuard { - unsafe fn as_mutex_guard(&self) -> &StaticMutexGuard { self } -} - -#[unsafe_destructor] -impl Drop for StaticMutexGuard { - fn drop(&mut self) { - unsafe { - self.poison.done(); - self.lock.unlock(); - } - } +pub fn guard_poison<'a, T>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag { + &guard.__lock.poison } #[cfg(test)] @@ -292,16 +333,16 @@ mod test { #[test] fn smoke() { let m = Mutex::new(()); - drop(m.lock()); - drop(m.lock()); + drop(m.lock().unwrap()); + drop(m.lock().unwrap()); } #[test] fn smoke_static() { static M: StaticMutex = MUTEX_INIT; unsafe { - drop(M.lock()); - drop(M.lock()); + drop(M.lock().unwrap()); + drop(M.lock().unwrap()); M.destroy(); } } @@ -316,7 +357,7 @@ mod test { fn inc() { for _ in range(0, J) { unsafe { - let _g = M.lock(); + let _g = M.lock().unwrap(); CNT += 1; } } @@ -343,7 +384,7 @@ mod test { #[test] fn try_lock() { let m = Mutex::new(()); - assert!(m.try_lock().is_some()); + *m.try_lock().unwrap() = (); } #[test] @@ -355,22 +396,21 @@ mod test { // wait until parent gets in rx.recv(); let &(ref lock, ref cvar) = &*packet2.0; - let mut lock = lock.lock(); + let mut lock = lock.lock().unwrap(); *lock = true; cvar.notify_one(); }); let &(ref lock, ref cvar) = &*packet.0; - let lock = lock.lock(); + let mut lock = lock.lock().unwrap(); tx.send(()); assert!(!*lock); while !*lock { - cvar.wait(&lock); + lock = cvar.wait(lock).unwrap(); } } #[test] - #[should_fail] fn test_arc_condvar_poison() { let packet = Packet(Arc::new((Mutex::new(1i), Condvar::new()))); let packet2 = Packet(packet.0.clone()); @@ -379,31 +419,35 @@ mod test { spawn(move|| { rx.recv(); let &(ref lock, ref cvar) = &*packet2.0; - let _g = lock.lock(); + let _g = lock.lock().unwrap(); cvar.notify_one(); // Parent should fail when it wakes up. panic!(); }); let &(ref lock, ref cvar) = &*packet.0; - let lock = lock.lock(); + let mut lock = lock.lock().unwrap(); tx.send(()); while *lock == 1 { - cvar.wait(&lock); + match cvar.wait(lock) { + Ok(l) => { + lock = l; + assert_eq!(*lock, 1); + } + Err(..) => break, + } } } #[test] - #[should_fail] fn test_mutex_arc_poison() { let arc = Arc::new(Mutex::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| { - let lock = arc2.lock(); + Thread::spawn(move|| { + let lock = arc2.lock().unwrap(); assert_eq!(*lock, 2); }).join(); - let lock = arc.lock(); - assert_eq!(*lock, 1); + assert!(arc.lock().is_err()); } #[test] @@ -414,8 +458,8 @@ mod test { let arc2 = Arc::new(Mutex::new(arc)); let (tx, rx) = channel(); spawn(move|| { - let lock = arc2.lock(); - let lock2 = lock.deref().lock(); + let lock = arc2.lock().unwrap(); + let lock2 = lock.deref().lock().unwrap(); assert_eq!(*lock2, 1); tx.send(()); }); @@ -432,13 +476,13 @@ mod test { } impl Drop for Unwinder { fn drop(&mut self) { - *self.i.lock() += 1; + *self.i.lock().unwrap() += 1; } } let _u = Unwinder { i: arc2 }; panic!(); }).join(); - let lock = arc.lock(); + let lock = arc.lock().unwrap(); assert_eq!(*lock, 2); } } diff --git a/src/libstd/sync/poison.rs b/src/libstd/sync/poison.rs index ad08e9873fa..edf16d99f49 100644 --- a/src/libstd/sync/poison.rs +++ b/src/libstd/sync/poison.rs @@ -8,31 +8,127 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use prelude::*; + +use cell::UnsafeCell; +use error::FromError; +use fmt; use thread::Thread; -pub struct Flag { pub failed: bool } +pub struct Flag { failed: UnsafeCell<bool> } +pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } }; impl Flag { - pub fn borrow(&mut self) -> Guard { - Guard { flag: &mut self.failed, panicking: Thread::panicking() } + #[inline] + pub fn borrow(&self) -> LockResult<Guard> { + let ret = Guard { panicking: Thread::panicking() }; + if unsafe { *self.failed.get() } { + Err(new_poison_error(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<'a> { - flag: &'a mut bool, +#[allow(missing_copy_implementations)] +pub struct Guard { panicking: bool, } -impl<'a> Guard<'a> { - pub fn check(&self, name: &str) { - if *self.flag { - panic!("poisoned {} - another task failed inside", name); - } +/// 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] +pub struct PoisonError<T> { + guard: T, +} + +/// An enumeration of possible errors which can occur while calling the +/// `try_lock` method. +#[stable] +pub enum TryLockError<T> { + /// The lock could not be acquired because another task failed while holding + /// the lock. + #[stable] + Poisoned(PoisonError<T>), + /// The lock could not be acquired at this time because the operation would + /// otherwise block. + #[stable] + 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] +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] +pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>; + +impl<T> fmt::Show for PoisonError<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + "poisoned lock: another task failed inside".fmt(f) + } +} + +impl<T> PoisonError<T> { + /// Consumes this error indicating that a lock is poisoned, returning the + /// underlying guard to allow access regardless. + #[stable] + pub fn into_guard(self) -> T { self.guard } +} + +impl<T> FromError<PoisonError<T>> for TryLockError<T> { + fn from_error(err: PoisonError<T>) -> TryLockError<T> { + TryLockError::Poisoned(err) } +} - pub fn done(&mut self) { - if !self.panicking && Thread::panicking() { - *self.flag = true; +impl<T> fmt::Show for TryLockError<T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + TryLockError::Poisoned(ref p) => p.fmt(f), + TryLockError::WouldBlock => { + "try_lock failed because the operation would block".fmt(f) + } } } } + +pub fn new_poison_error<T>(guard: T) -> PoisonError<T> { + PoisonError { guard: guard } +} + +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(new_poison_error(f(guard))) + } +} diff --git a/src/libstd/sync/rwlock.rs b/src/libstd/sync/rwlock.rs index 76d05d9bfd4..7f3c77c97ad 100644 --- a/src/libstd/sync/rwlock.rs +++ b/src/libstd/sync/rwlock.rs @@ -10,10 +10,10 @@ use prelude::*; -use kinds::marker; use cell::UnsafeCell; +use kinds::marker; +use sync::poison::{mod, LockResult, TryLockError, TryLockResult}; use sys_common::rwlock as sys; -use sync::poison; /// A reader-writer lock /// @@ -28,12 +28,14 @@ use sync::poison; /// locking methods implement `Deref` (and `DerefMut` for the `write` methods) /// to allow access to the contained of the lock. /// +/// # Poisoning +/// /// RWLocks, like Mutexes, will become poisoned on panics. Note, however, that /// an RWLock may only be poisoned if a panic occurs while it is locked /// exclusively (write mode). If a panic occurs in any reader, then the lock /// will not be poisoned. /// -/// # Example +/// # Examples /// /// ``` /// use std::sync::RWLock; @@ -42,19 +44,20 @@ use sync::poison; /// /// // many reader locks can be held at once /// { -/// let r1 = lock.read(); -/// let r2 = lock.read(); +/// let r1 = lock.read().unwrap(); +/// let r2 = lock.read().unwrap(); /// assert_eq!(*r1, 5); /// assert_eq!(*r2, 5); /// } // read locks are dropped at this point /// /// // only one write lock may be held, however /// { -/// let mut w = lock.write(); +/// let mut w = lock.write().unwrap(); /// *w += 1; /// assert_eq!(*w, 6); /// } // write lock is dropped here /// ``` +#[stable] pub struct RWLock<T> { inner: Box<StaticRWLock>, data: UnsafeCell<T>, @@ -77,64 +80,55 @@ unsafe impl<T> Sync for RWLock<T> {} /// static LOCK: StaticRWLock = RWLOCK_INIT; /// /// { -/// let _g = LOCK.read(); +/// let _g = LOCK.read().unwrap(); /// // ... shared read access /// } /// { -/// let _g = LOCK.write(); +/// let _g = LOCK.write().unwrap(); /// // ... exclusive write access /// } /// unsafe { LOCK.destroy() } // free all resources /// ``` +#[unstable = "may be merged with RWLock in the future"] pub struct StaticRWLock { - inner: sys::RWLock, - poison: UnsafeCell<poison::Flag>, + lock: sys::RWLock, + poison: poison::Flag, } unsafe impl Send for StaticRWLock {} unsafe impl Sync for StaticRWLock {} /// Constant initialization for a statically-initialized rwlock. +#[unstable = "may be merged with RWLock in the future"] pub const RWLOCK_INIT: StaticRWLock = StaticRWLock { - inner: sys::RWLOCK_INIT, - poison: UnsafeCell { value: poison::Flag { failed: false } }, + lock: sys::RWLOCK_INIT, + poison: poison::FLAG_INIT, }; /// RAII structure used to release the shared read access of a lock when /// dropped. #[must_use] +#[stable] pub struct RWLockReadGuard<'a, T: 'a> { - __lock: &'a RWLock<T>, - __guard: StaticRWLockReadGuard, + __lock: &'a StaticRWLock, + __data: &'a UnsafeCell<T>, + __marker: marker::NoSend, } /// RAII structure used to release the exclusive write access of a lock when /// dropped. #[must_use] +#[stable] pub struct RWLockWriteGuard<'a, T: 'a> { - __lock: &'a RWLock<T>, - __guard: StaticRWLockWriteGuard, -} - -/// RAII structure used to release the shared read access of a lock when -/// dropped. -#[must_use] -pub struct StaticRWLockReadGuard { - lock: &'static sys::RWLock, - marker: marker::NoSend, -} - -/// RAII structure used to release the exclusive write access of a lock when -/// dropped. -#[must_use] -pub struct StaticRWLockWriteGuard { - lock: &'static sys::RWLock, - marker: marker::NoSend, - poison: poison::Guard<'static>, + __lock: &'a StaticRWLock, + __data: &'a UnsafeCell<T>, + __poison: poison::Guard, + __marker: marker::NoSend, } impl<T: Send + Sync> RWLock<T> { /// Creates a new instance of an RWLock which is unlocked and read to go. + #[stable] pub fn new(t: T) -> RWLock<T> { RWLock { inner: box RWLOCK_INIT, data: UnsafeCell::new(t) } } @@ -151,17 +145,16 @@ impl<T: Send + Sync> RWLock<T> { /// Returns an RAII guard which will release this thread's shared access /// once it is dropped. /// - /// # Panics + /// # Failure /// - /// This function will panic if the RWLock is poisoned. An RWLock is - /// poisoned whenever a writer panics while holding an exclusive lock. The - /// panic will occur immediately after the lock has been acquired. + /// This function will return an error if the RWLock is poisoned. An RWLock + /// is poisoned whenever a writer panics while holding an exclusive lock. + /// The failure will occur immediately after the lock has been acquired. #[inline] - pub fn read(&self) -> RWLockReadGuard<T> { - unsafe { - let lock: &'static StaticRWLock = &*(&*self.inner as *const _); - RWLockReadGuard::new(self, lock.read()) - } + #[stable] + pub fn read(&self) -> LockResult<RWLockReadGuard<T>> { + unsafe { self.inner.lock.read() } + RWLockReadGuard::new(&*self.inner, &self.data) } /// Attempt to acquire this lock with shared read access. @@ -173,18 +166,19 @@ impl<T: Send + Sync> RWLock<T> { /// guarantees with respect to the ordering of whether contentious readers /// or writers will acquire the lock first. /// - /// # Panics + /// # Failure /// - /// This function will panic if the RWLock is poisoned. An RWLock is - /// poisoned whenever a writer panics while holding an exclusive lock. A - /// panic will only occur if the lock is acquired. + /// This function will return an error if the RWLock is poisoned. An RWLock + /// is poisoned whenever a writer panics while holding an exclusive lock. An + /// error will only be returned if the lock would have otherwise been + /// acquired. #[inline] - pub fn try_read(&self) -> Option<RWLockReadGuard<T>> { - unsafe { - let lock: &'static StaticRWLock = &*(&*self.inner as *const _); - lock.try_read().map(|guard| { - RWLockReadGuard::new(self, guard) - }) + #[stable] + pub fn try_read(&self) -> TryLockResult<RWLockReadGuard<T>> { + if unsafe { self.inner.lock.try_read() } { + Ok(try!(RWLockReadGuard::new(&*self.inner, &self.data))) + } else { + Err(TryLockError::WouldBlock) } } @@ -197,17 +191,16 @@ impl<T: Send + Sync> RWLock<T> { /// Returns an RAII guard which will drop the write access of this rwlock /// when dropped. /// - /// # Panics + /// # Failure /// - /// This function will panic if the RWLock is poisoned. An RWLock is - /// poisoned whenever a writer panics while holding an exclusive lock. The - /// panic will occur when the lock is acquired. + /// This function will return an error if the RWLock is poisoned. An RWLock + /// is poisoned whenever a writer panics while holding an exclusive lock. + /// An error will be returned when the lock is acquired. #[inline] - pub fn write(&self) -> RWLockWriteGuard<T> { - unsafe { - let lock: &'static StaticRWLock = &*(&*self.inner as *const _); - RWLockWriteGuard::new(self, lock.write()) - } + #[stable] + pub fn write(&self) -> LockResult<RWLockWriteGuard<T>> { + unsafe { self.inner.lock.write() } + RWLockWriteGuard::new(&*self.inner, &self.data) } /// Attempt to lock this rwlock with exclusive write access. @@ -216,18 +209,19 @@ impl<T: Send + Sync> RWLock<T> { /// to `write` would otherwise block. If successful, an RAII guard is /// returned. /// - /// # Panics + /// # Failure /// - /// This function will panic if the RWLock is poisoned. An RWLock is - /// poisoned whenever a writer panics while holding an exclusive lock. A - /// panic will only occur if the lock is acquired. + /// This function will return an error if the RWLock is poisoned. An RWLock + /// is poisoned whenever a writer panics while holding an exclusive lock. An + /// error will only be returned if the lock would have otherwise been + /// acquired. #[inline] - pub fn try_write(&self) -> Option<RWLockWriteGuard<T>> { - unsafe { - let lock: &'static StaticRWLock = &*(&*self.inner as *const _); - lock.try_write().map(|guard| { - RWLockWriteGuard::new(self, guard) - }) + #[stable] + pub fn try_write(&self) -> TryLockResult<RWLockWriteGuard<T>> { + if unsafe { self.inner.lock.try_read() } { + Ok(try!(RWLockWriteGuard::new(&*self.inner, &self.data))) + } else { + Err(TryLockError::WouldBlock) } } } @@ -235,30 +229,37 @@ impl<T: Send + Sync> RWLock<T> { #[unsafe_destructor] impl<T> Drop for RWLock<T> { fn drop(&mut self) { - unsafe { self.inner.inner.destroy() } + unsafe { self.inner.lock.destroy() } } } +struct Dummy(UnsafeCell<()>); +unsafe impl Sync for Dummy {} +static DUMMY: Dummy = Dummy(UnsafeCell { value: () }); + impl StaticRWLock { /// Locks this rwlock with shared read access, blocking the current thread /// until it can be acquired. /// /// See `RWLock::read`. #[inline] - pub fn read(&'static self) -> StaticRWLockReadGuard { - unsafe { self.inner.read() } - StaticRWLockReadGuard::new(self) + #[unstable = "may be merged with RWLock in the future"] + pub fn read(&'static self) -> LockResult<RWLockReadGuard<'static, ()>> { + unsafe { self.lock.read() } + RWLockReadGuard::new(self, &DUMMY.0) } /// Attempt to acquire this lock with shared read access. /// /// See `RWLock::try_read`. #[inline] - pub fn try_read(&'static self) -> Option<StaticRWLockReadGuard> { - if unsafe { self.inner.try_read() } { - Some(StaticRWLockReadGuard::new(self)) + #[unstable = "may be merged with RWLock in the future"] + pub fn try_read(&'static self) + -> TryLockResult<RWLockReadGuard<'static, ()>> { + if unsafe { self.lock.try_read() } { + Ok(try!(RWLockReadGuard::new(self, &DUMMY.0))) } else { - None + Err(TryLockError::WouldBlock) } } @@ -267,20 +268,23 @@ impl StaticRWLock { /// /// See `RWLock::write`. #[inline] - pub fn write(&'static self) -> StaticRWLockWriteGuard { - unsafe { self.inner.write() } - StaticRWLockWriteGuard::new(self) + #[unstable = "may be merged with RWLock in the future"] + pub fn write(&'static self) -> LockResult<RWLockWriteGuard<'static, ()>> { + unsafe { self.lock.write() } + RWLockWriteGuard::new(self, &DUMMY.0) } /// Attempt to lock this rwlock with exclusive write access. /// /// See `RWLock::try_write`. #[inline] - pub fn try_write(&'static self) -> Option<StaticRWLockWriteGuard> { - if unsafe { self.inner.try_write() } { - Some(StaticRWLockWriteGuard::new(self)) + #[unstable = "may be merged with RWLock in the future"] + pub fn try_write(&'static self) + -> TryLockResult<RWLockWriteGuard<'static, ()>> { + if unsafe { self.lock.try_write() } { + Ok(try!(RWLockWriteGuard::new(self, &DUMMY.0))) } else { - None + Err(TryLockError::WouldBlock) } } @@ -290,70 +294,62 @@ impl StaticRWLock { /// active users of the lock, and this also doesn't prevent any future users /// of this lock. This method is required to be called to not leak memory on /// all platforms. + #[unstable = "may be merged with RWLock in the future"] pub unsafe fn destroy(&'static self) { - self.inner.destroy() + self.lock.destroy() } } impl<'rwlock, T> RWLockReadGuard<'rwlock, T> { - fn new(lock: &RWLock<T>, guard: StaticRWLockReadGuard) - -> RWLockReadGuard<T> { - RWLockReadGuard { __lock: lock, __guard: guard } + fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell<T>) + -> LockResult<RWLockReadGuard<'rwlock, T>> { + poison::map_result(lock.poison.borrow(), |_| { + RWLockReadGuard { + __lock: lock, + __data: data, + __marker: marker::NoSend, + } + }) } } impl<'rwlock, T> RWLockWriteGuard<'rwlock, T> { - fn new(lock: &RWLock<T>, guard: StaticRWLockWriteGuard) - -> RWLockWriteGuard<T> { - RWLockWriteGuard { __lock: lock, __guard: guard } + fn new(lock: &'rwlock StaticRWLock, data: &'rwlock UnsafeCell<T>) + -> LockResult<RWLockWriteGuard<'rwlock, T>> { + poison::map_result(lock.poison.borrow(), |guard| { + RWLockWriteGuard { + __lock: lock, + __data: data, + __poison: guard, + __marker: marker::NoSend, + } + }) } } impl<'rwlock, T> Deref<T> for RWLockReadGuard<'rwlock, T> { - fn deref(&self) -> &T { unsafe { &*self.__lock.data.get() } } + fn deref(&self) -> &T { unsafe { &*self.__data.get() } } } impl<'rwlock, T> Deref<T> for RWLockWriteGuard<'rwlock, T> { - fn deref(&self) -> &T { unsafe { &*self.__lock.data.get() } } + fn deref(&self) -> &T { unsafe { &*self.__data.get() } } } impl<'rwlock, T> DerefMut<T> for RWLockWriteGuard<'rwlock, T> { - fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.__lock.data.get() } } -} - -impl StaticRWLockReadGuard { - fn new(lock: &'static StaticRWLock) -> StaticRWLockReadGuard { - let guard = StaticRWLockReadGuard { - lock: &lock.inner, - marker: marker::NoSend, - }; - unsafe { (*lock.poison.get()).borrow().check("rwlock"); } - return guard; - } -} -impl StaticRWLockWriteGuard { - fn new(lock: &'static StaticRWLock) -> StaticRWLockWriteGuard { - unsafe { - let guard = StaticRWLockWriteGuard { - lock: &lock.inner, - marker: marker::NoSend, - poison: (*lock.poison.get()).borrow(), - }; - guard.poison.check("rwlock"); - return guard; - } + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.__data.get() } } } #[unsafe_destructor] -impl Drop for StaticRWLockReadGuard { +impl<'a, T> Drop for RWLockReadGuard<'a, T> { fn drop(&mut self) { - unsafe { self.lock.read_unlock(); } + unsafe { self.__lock.lock.read_unlock(); } } } #[unsafe_destructor] -impl Drop for StaticRWLockWriteGuard { +impl<'a, T> Drop for RWLockWriteGuard<'a, T> { fn drop(&mut self) { - self.poison.done(); - unsafe { self.lock.write_unlock(); } + self.__lock.poison.done(&self.__poison); + unsafe { self.__lock.lock.write_unlock(); } } } @@ -368,19 +364,19 @@ mod tests { #[test] fn smoke() { let l = RWLock::new(()); - drop(l.read()); - drop(l.write()); - drop((l.read(), l.read())); - drop(l.write()); + drop(l.read().unwrap()); + drop(l.write().unwrap()); + drop((l.read().unwrap(), l.read().unwrap())); + drop(l.write().unwrap()); } #[test] fn static_smoke() { static R: StaticRWLock = RWLOCK_INIT; - drop(R.read()); - drop(R.write()); - drop((R.read(), R.read())); - drop(R.write()); + drop(R.read().unwrap()); + drop(R.write().unwrap()); + drop((R.read().unwrap(), R.read().unwrap())); + drop(R.write().unwrap()); unsafe { R.destroy(); } } @@ -394,12 +390,12 @@ mod tests { for _ in range(0, N) { let tx = tx.clone(); spawn(move|| { - let mut rng = rand::task_rng(); + let mut rng = rand::thread_rng(); for _ in range(0, M) { if rng.gen_weighted_bool(N) { - drop(R.write()); + drop(R.write().unwrap()); } else { - drop(R.read()); + drop(R.read().unwrap()); } } drop(tx); @@ -411,51 +407,47 @@ mod tests { } #[test] - #[should_fail] fn test_rw_arc_poison_wr() { let arc = Arc::new(RWLock::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| { - let lock = arc2.write(); - assert_eq!(*lock, 2); + let _: Result<uint, _> = Thread::spawn(move|| { + let _lock = arc2.write().unwrap(); + panic!(); }).join(); - let lock = arc.read(); - assert_eq!(*lock, 1); + assert!(arc.read().is_err()); } #[test] - #[should_fail] fn test_rw_arc_poison_ww() { let arc = Arc::new(RWLock::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| { - let lock = arc2.write(); - assert_eq!(*lock, 2); + let _: Result<uint, _> = Thread::spawn(move|| { + let _lock = arc2.write().unwrap(); + panic!(); }).join(); - let lock = arc.write(); - assert_eq!(*lock, 1); + assert!(arc.write().is_err()); } #[test] fn test_rw_arc_no_poison_rr() { let arc = Arc::new(RWLock::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| { - let lock = arc2.read(); - assert_eq!(*lock, 2); + let _: Result<uint, _> = Thread::spawn(move|| { + let _lock = arc2.read().unwrap(); + panic!(); }).join(); - let lock = arc.read(); + let lock = arc.read().unwrap(); assert_eq!(*lock, 1); } #[test] fn test_rw_arc_no_poison_rw() { let arc = Arc::new(RWLock::new(1i)); let arc2 = arc.clone(); - let _ = Thread::spawn(move|| { - let lock = arc2.read(); - assert_eq!(*lock, 2); + let _: Result<uint, _> = Thread::spawn(move|| { + let _lock = arc2.read().unwrap(); + panic!() }).join(); - let lock = arc.write(); + let lock = arc.write().unwrap(); assert_eq!(*lock, 1); } @@ -466,7 +458,7 @@ mod tests { let (tx, rx) = channel(); Thread::spawn(move|| { - let mut lock = arc2.write(); + let mut lock = arc2.write().unwrap(); for _ in range(0u, 10) { let tmp = *lock; *lock = -1; @@ -481,7 +473,7 @@ mod tests { for _ in range(0u, 5) { let arc3 = arc.clone(); children.push(Thread::spawn(move|| { - let lock = arc3.read(); + let lock = arc3.read().unwrap(); assert!(*lock >= 0); })); } @@ -493,7 +485,7 @@ mod tests { // Wait for writer to finish rx.recv(); - let lock = arc.read(); + let lock = arc.read().unwrap(); assert_eq!(*lock, 10); } @@ -507,14 +499,14 @@ mod tests { } impl Drop for Unwinder { fn drop(&mut self) { - let mut lock = self.i.write(); + let mut lock = self.i.write().unwrap(); *lock += 1; } } let _u = Unwinder { i: arc2 }; panic!(); }).join(); - let lock = arc.read(); + let lock = arc.read().unwrap(); assert_eq!(*lock, 2); } } diff --git a/src/libstd/sync/semaphore.rs b/src/libstd/sync/semaphore.rs index 574b0f22bee..e3b683a6ccb 100644 --- a/src/libstd/sync/semaphore.rs +++ b/src/libstd/sync/semaphore.rs @@ -68,9 +68,9 @@ impl Semaphore { /// This method will block until the internal count of the semaphore is at /// least 1. pub fn acquire(&self) { - let mut count = self.lock.lock(); + let mut count = self.lock.lock().unwrap(); while *count <= 0 { - self.cvar.wait(&count); + count = self.cvar.wait(count).unwrap(); } *count -= 1; } @@ -80,7 +80,7 @@ impl Semaphore { /// This will increment the number of resources in this semaphore by 1 and /// will notify any pending waiters in `acquire` or `access` if necessary. pub fn release(&self) { - *self.lock.lock() += 1; + *self.lock.lock().unwrap() += 1; self.cvar.notify_one(); } diff --git a/src/libstd/sync/task_pool.rs b/src/libstd/sync/task_pool.rs index 366e4b7d35b..ee534f6cdde 100644 --- a/src/libstd/sync/task_pool.rs +++ b/src/libstd/sync/task_pool.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -//! Abstraction of a task pool for basic parallelism. +//! Abstraction of a thread pool for basic parallelism. use core::prelude::*; @@ -45,9 +45,9 @@ impl<'a> Drop for Sentinel<'a> { } } -/// A task pool used to execute functions in parallel. +/// A thread pool used to execute functions in parallel. /// -/// Spawns `n` worker tasks and replenishes the pool if any worker tasks +/// Spawns `n` worker threads and replenishes the pool if any worker threads /// panic. /// /// # Example @@ -69,34 +69,34 @@ impl<'a> Drop for Sentinel<'a> { /// assert_eq!(rx.iter().take(8u).sum(), 8u); /// ``` pub struct TaskPool { - // How the taskpool communicates with subtasks. + // How the threadpool communicates with subthreads. // - // This is the only such Sender, so when it is dropped all subtasks will + // This is the only such Sender, so when it is dropped all subthreads will // quit. jobs: Sender<Thunk> } impl TaskPool { - /// Spawns a new task pool with `tasks` tasks. + /// Spawns a new thread pool with `threads` threads. /// /// # Panics /// - /// This function will panic if `tasks` is 0. - pub fn new(tasks: uint) -> TaskPool { - assert!(tasks >= 1); + /// This function will panic if `threads` is 0. + pub fn new(threads: uint) -> TaskPool { + assert!(threads >= 1); let (tx, rx) = channel::<Thunk>(); let rx = Arc::new(Mutex::new(rx)); - // Taskpool tasks. - for _ in range(0, tasks) { + // Threadpool threads + for _ in range(0, threads) { spawn_in_pool(rx.clone()); } TaskPool { jobs: tx } } - /// Executes the function `job` on a task in the pool. + /// Executes the function `job` on a thread in the pool. pub fn execute<F>(&self, job: F) where F : FnOnce(), F : Send { @@ -106,14 +106,14 @@ impl TaskPool { fn spawn_in_pool(jobs: Arc<Mutex<Receiver<Thunk>>>) { Thread::spawn(move |:| { - // Will spawn a new task on panic unless it is cancelled. + // Will spawn a new thread on panic unless it is cancelled. let sentinel = Sentinel::new(&jobs); loop { let message = { // Only lock jobs for the time it takes // to get a job, not run it. - let lock = jobs.lock(); + let lock = jobs.lock().unwrap(); lock.recv_opt() }; @@ -165,12 +165,12 @@ mod test { let pool = TaskPool::new(TEST_TASKS); - // Panic all the existing tasks. + // Panic all the existing threads. for _ in range(0, TEST_TASKS) { pool.execute(move|| -> () { panic!() }); } - // Ensure new tasks were spawned to compensate. + // Ensure new threads were spawned to compensate. let (tx, rx) = channel(); for _ in range(0, TEST_TASKS) { let tx = tx.clone(); @@ -189,7 +189,7 @@ mod test { let pool = TaskPool::new(TEST_TASKS); let waiter = Arc::new(Barrier::new(TEST_TASKS + 1)); - // Panic all the existing tasks in a bit. + // Panic all the existing threads in a bit. for _ in range(0, TEST_TASKS) { let waiter = waiter.clone(); pool.execute(move|| { diff --git a/src/libstd/sys/common/backtrace.rs b/src/libstd/sys/common/backtrace.rs index 1d646eb06b1..866bf1d8a7d 100644 --- a/src/libstd/sys/common/backtrace.rs +++ b/src/libstd/sys/common/backtrace.rs @@ -115,10 +115,10 @@ pub fn demangle(writer: &mut Writer, s: &str) -> IoResult<()> { // in theory we can demangle any Unicode code point, but // for simplicity we just catch the common ones. - "$x20" => " ", - "$x27" => "'", - "$x5b" => "[", - "$x5d" => "]" + "$u{20}" => " ", + "$u{27}" => "'", + "$u{5b}" => "[", + "$u{5d}" => "]" ) } else { let idx = match rest.find('$') { diff --git a/src/libstd/sys/common/helper_thread.rs b/src/libstd/sys/common/helper_thread.rs index a629f035b07..9ef1c33312f 100644 --- a/src/libstd/sys/common/helper_thread.rs +++ b/src/libstd/sys/common/helper_thread.rs @@ -83,7 +83,7 @@ impl<M: Send> Helper<M> { F: FnOnce() -> T, { unsafe { - let _guard = self.lock.lock(); + let _guard = self.lock.lock().unwrap(); if !*self.initialized.get() { let (tx, rx) = channel(); *self.chan.get() = mem::transmute(box tx); @@ -95,7 +95,7 @@ impl<M: Send> Helper<M> { let t = f(); Thread::spawn(move |:| { helper(receive.0, rx, t); - let _g = self.lock.lock(); + let _g = self.lock.lock().unwrap(); *self.shutdown.get() = true; self.cond.notify_one() }).detach(); @@ -111,7 +111,7 @@ impl<M: Send> Helper<M> { /// This is only valid if the worker thread has previously booted pub fn send(&'static self, msg: M) { unsafe { - let _guard = self.lock.lock(); + let _guard = self.lock.lock().unwrap(); // Must send and *then* signal to ensure that the child receives the // message. Otherwise it could wake up and go to sleep before we @@ -127,7 +127,7 @@ impl<M: Send> Helper<M> { // Shut down, but make sure this is done inside our lock to ensure // that we'll always receive the exit signal when the thread // returns. - let guard = self.lock.lock(); + let mut guard = self.lock.lock().unwrap(); // Close the channel by destroying it let chan: Box<Sender<M>> = mem::transmute(*self.chan.get()); @@ -137,7 +137,7 @@ impl<M: Send> Helper<M> { // Wait for the child to exit while !*self.shutdown.get() { - self.cond.wait(&guard); + guard = self.cond.wait(guard).unwrap(); } drop(guard); diff --git a/src/libstd/sys/common/net.rs b/src/libstd/sys/common/net.rs index 382f6875b28..7a09137a225 100644 --- a/src/libstd/sys/common/net.rs +++ b/src/libstd/sys/common/net.rs @@ -269,7 +269,7 @@ pub fn get_host_addresses(host: Option<&str>, servname: Option<&str>, // Collect all the results we found let mut addrs = Vec::new(); let mut rp = res; - while rp.is_not_null() { + while !rp.is_null() { unsafe { let addr = try!(sockaddr_to_addr(mem::transmute((*rp).ai_addr), (*rp).ai_addrlen as uint)); @@ -669,7 +669,7 @@ impl TcpStream { fn lock_nonblocking<'a>(&'a self) -> Guard<'a> { let ret = Guard { fd: self.fd(), - guard: self.inner.lock.lock(), + guard: self.inner.lock.lock().unwrap(), }; assert!(set_nonblocking(self.fd(), true).is_ok()); ret @@ -808,7 +808,7 @@ impl UdpSocket { fn lock_nonblocking<'a>(&'a self) -> Guard<'a> { let ret = Guard { fd: self.fd(), - guard: self.inner.lock.lock(), + guard: self.inner.lock.lock().unwrap(), }; assert!(set_nonblocking(self.fd(), true).is_ok()); ret diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index 983d0e5fa14..ddae9a132c3 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -244,7 +244,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { use iter::{Iterator, IteratorExt}; use os; use path::GenericPath; - use ptr::RawPtr; + use ptr::PtrExt; use ptr; use slice::SliceExt; diff --git a/src/libstd/sys/unix/mod.rs b/src/libstd/sys/unix/mod.rs index f3babca3287..4b7ac8ff4d3 100644 --- a/src/libstd/sys/unix/mod.rs +++ b/src/libstd/sys/unix/mod.rs @@ -109,6 +109,8 @@ pub fn decode_error(errno: i32) -> IoError { "file descriptor is not a TTY"), libc::ETIMEDOUT => (io::TimedOut, "operation timed out"), libc::ECANCELED => (io::TimedOut, "operation aborted"), + libc::consts::os::posix88::EEXIST => + (io::PathAlreadyExists, "path already exists"), // These two constants can have the same value on some systems, // but different values on others, so we can't use a match diff --git a/src/libstd/sys/unix/pipe.rs b/src/libstd/sys/unix/pipe.rs index f1b078b4e80..868b460aa5e 100644 --- a/src/libstd/sys/unix/pipe.rs +++ b/src/libstd/sys/unix/pipe.rs @@ -145,7 +145,7 @@ impl UnixStream { fn lock_nonblocking<'a>(&'a self) -> Guard<'a> { let ret = Guard { fd: self.fd(), - guard: unsafe { self.inner.lock.lock() }, + guard: unsafe { self.inner.lock.lock().unwrap() }, }; assert!(set_nonblocking(self.fd(), true).is_ok()); ret diff --git a/src/libstd/sys/windows/c.rs b/src/libstd/sys/windows/c.rs index d1cb91bcdb3..06259d61fcb 100644 --- a/src/libstd/sys/windows/c.rs +++ b/src/libstd/sys/windows/c.rs @@ -131,7 +131,6 @@ extern "system" { pub mod compat { use intrinsics::{atomic_store_relaxed, transmute}; - use iter::IteratorExt; use libc::types::os::arch::extra::{LPCWSTR, HMODULE, LPCSTR, LPVOID}; use prelude::*; diff --git a/src/libstd/sys/windows/fs.rs b/src/libstd/sys/windows/fs.rs index 15eddd569be..3ad439078b9 100644 --- a/src/libstd/sys/windows/fs.rs +++ b/src/libstd/sys/windows/fs.rs @@ -265,8 +265,8 @@ pub fn readdir(p: &Path) -> IoResult<Vec<Path>> { { let filename = os::truncate_utf16_at_nul(&wfd.cFileName); match String::from_utf16(filename) { - Some(filename) => paths.push(Path::new(filename)), - None => { + Ok(filename) => paths.push(Path::new(filename)), + Err(..) => { assert!(libc::FindClose(find_handle) != 0); return Err(IoError { kind: io::InvalidInput, diff --git a/src/libstd/sys/windows/mod.rs b/src/libstd/sys/windows/mod.rs index 6924687d8c4..aee98e22836 100644 --- a/src/libstd/sys/windows/mod.rs +++ b/src/libstd/sys/windows/mod.rs @@ -121,6 +121,8 @@ pub fn decode_error(errno: i32) -> IoError { "invalid handle provided to function"), libc::ERROR_NOTHING_TO_TERMINATE => (io::InvalidInput, "no process to kill"), + libc::ERROR_ALREADY_EXISTS => + (io::PathAlreadyExists, "path already exists"), // libuv maps this error code to EISDIR. we do too. if it is found // to be incorrect, we can add in some more machinery to only diff --git a/src/libstd/sys/windows/os.rs b/src/libstd/sys/windows/os.rs index e007b46b261..fa08290a888 100644 --- a/src/libstd/sys/windows/os.rs +++ b/src/libstd/sys/windows/os.rs @@ -99,8 +99,9 @@ pub fn error_string(errnum: i32) -> String { let msg = String::from_utf16(truncate_utf16_at_nul(&buf)); match msg { - Some(msg) => format!("OS Error {}: {}", errnum, msg), - None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum), + Ok(msg) => format!("OS Error {}: {}", errnum, msg), + Err(..) => format!("OS Error {} (FormatMessageW() returned \ + invalid UTF-16)", errnum), } } } @@ -147,7 +148,7 @@ pub fn fill_utf16_buf_and_decode(f: |*mut u16, DWORD| -> DWORD) -> Option<String // We want to explicitly catch the case when the // closure returned invalid UTF-16, rather than // set `res` to None and continue. - let s = String::from_utf16(sub) + let s = String::from_utf16(sub).ok() .expect("fill_utf16_buf_and_decode: closure created invalid UTF-16"); res = Some(s) } @@ -169,8 +170,8 @@ pub fn getcwd() -> IoResult<Path> { } match String::from_utf16(truncate_utf16_at_nul(&buf)) { - Some(ref cwd) => Ok(Path::new(cwd)), - None => Err(IoError { + Ok(ref cwd) => Ok(Path::new(cwd)), + Err(..) => Err(IoError { kind: OtherIoError, desc: "GetCurrentDirectoryW returned invalid UTF-16", detail: None, diff --git a/src/libstd/sys/windows/tty.rs b/src/libstd/sys/windows/tty.rs index f793de5bb57..99292b3b44b 100644 --- a/src/libstd/sys/windows/tty.rs +++ b/src/libstd/sys/windows/tty.rs @@ -101,8 +101,8 @@ impl TTY { }; utf16.truncate(num as uint); let utf8 = match String::from_utf16(utf16.as_slice()) { - Some(utf8) => utf8.into_bytes(), - None => return Err(invalid_encoding()), + Ok(utf8) => utf8.into_bytes(), + Err(..) => return Err(invalid_encoding()), }; self.utf8 = MemReader::new(utf8); } diff --git a/src/libstd/thread.rs b/src/libstd/thread.rs index 56731bd7ec3..a7b3ee996a3 100644 --- a/src/libstd/thread.rs +++ b/src/libstd/thread.rs @@ -313,7 +313,7 @@ impl Thread { /// Spawn a new joinable thread, returning a `JoinGuard` for it. /// - /// The join guard can be used to explicitly join the child thead (via + /// The join guard can be used to explicitly join the child thread (via /// `join`), returning `Result<T>`, or it will implicitly join the child /// upon being dropped. To detach the child, allowing it to outlive the /// current thread, use `detach`. See the module documentation for additional details. @@ -334,6 +334,7 @@ impl Thread { } /// Determines whether the current thread is panicking. + #[inline] pub fn panicking() -> bool { unwind::panicking() } @@ -349,9 +350,9 @@ impl Thread { // or futuxes, and in either case may allow spurious wakeups. pub fn park() { let thread = Thread::current(); - let mut guard = thread.inner.lock.lock(); + let mut guard = thread.inner.lock.lock().unwrap(); while !*guard { - thread.inner.cvar.wait(&guard); + guard = thread.inner.cvar.wait(guard).unwrap(); } *guard = false; } @@ -360,7 +361,7 @@ impl Thread { /// /// See the module doc for more detail. pub fn unpark(&self) { - let mut guard = self.inner.lock.lock(); + let mut guard = self.inner.lock.lock().unwrap(); if !*guard { *guard = true; self.inner.cvar.notify_one(); diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index 242dceb4256..4cfa2709352 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -240,13 +240,18 @@ impl<T: 'static> Key<T> { unsafe { let slot = slot.get().expect("cannot access a TLS value during or \ after it is destroyed"); - if (*slot.get()).is_none() { - *slot.get() = Some((self.init)()); - } - f((*slot.get()).as_ref().unwrap()) + f(match *slot.get() { + Some(ref inner) => inner, + None => self.init(slot), + }) } } + unsafe fn init(&self, slot: &UnsafeCell<Option<T>>) -> &T { + *slot.get() = Some((self.init)()); + (*slot.get()).as_ref().unwrap() + } + /// Test this TLS key to determine whether its value has been destroyed for /// the current thread or not. /// diff --git a/src/libstd/thread_local/scoped.rs b/src/libstd/thread_local/scoped.rs index 756c86c2115..5f96548c053 100644 --- a/src/libstd/thread_local/scoped.rs +++ b/src/libstd/thread_local/scoped.rs @@ -62,10 +62,10 @@ pub struct Key<T> { #[doc(hidden)] pub inner: KeyInner<T> } #[macro_export] macro_rules! scoped_thread_local { (static $name:ident: $t:ty) => ( - __scoped_thread_local_inner!(static $name: $t) + __scoped_thread_local_inner!(static $name: $t); ); (pub static $name:ident: $t:ty) => ( - __scoped_thread_local_inner!(pub static $name: $t) + __scoped_thread_local_inner!(pub static $name: $t); ); } @@ -240,6 +240,8 @@ mod tests { use cell::Cell; use prelude::*; + scoped_thread_local!(static FOO: uint); + #[test] fn smoke() { scoped_thread_local!(static BAR: uint); @@ -264,4 +266,16 @@ mod tests { }); }); } + + #[test] + fn scope_item_allowed() { + assert!(!FOO.is_set()); + FOO.set(&1, || { + assert!(FOO.is_set()); + FOO.with(|slot| { + assert_eq!(*slot, 1); + }); + }); + assert!(!FOO.is_set()); + } } |
