1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use sync::atomic::{AtomicBool, Ordering};
16 pub struct Flag { failed: AtomicBool }
18 // Note that the Ordering uses to access the `failed` field of `Flag` below is
19 // always `Relaxed`, and that's because this isn't actually protecting any data,
20 // it's just a flag whether we've panicked or not.
22 // The actual location that this matters is when a mutex is **locked** which is
23 // where we have external synchronization ensuring that we see memory
24 // reads/writes to this flag.
26 // As a result, if it matters, we should see the correct value for `failed` in
30 pub const fn new() -> Flag {
31 Flag { failed: AtomicBool::new(false) }
35 pub fn borrow(&self) -> LockResult<Guard> {
36 let ret = Guard { panicking: thread::panicking() };
38 Err(PoisonError::new(ret))
45 pub fn done(&self, guard: &Guard) {
46 if !guard.panicking && thread::panicking() {
47 self.failed.store(true, Ordering::Relaxed);
52 pub fn get(&self) -> bool {
53 self.failed.load(Ordering::Relaxed)
61 /// A type of error which can be returned whenever a lock is acquired.
63 /// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
64 /// is held. The precise semantics for when a lock is poisoned is documented on
65 /// each lock, but once a lock is poisoned then all future acquisitions will
66 /// return this error.
71 /// use std::sync::{Arc, Mutex};
74 /// let mutex = Arc::new(Mutex::new(1));
76 /// // poison the mutex
77 /// let c_mutex = mutex.clone();
78 /// let _ = thread::spawn(move || {
79 /// let mut data = c_mutex.lock().unwrap();
84 /// match mutex.lock() {
85 /// Ok(_) => unreachable!(),
87 /// let data = p_err.get_ref();
88 /// println!("recovered: {}", data);
93 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
94 /// [`RwLock`]: ../../std/sync/struct.RwLock.html
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct PoisonError<T> {
100 /// An enumeration of possible errors associated with a [`TryLockResult`] which
101 /// can occur while trying to acquire a lock, from the [`try_lock`] method on a
102 /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
104 /// [`Mutex`]: struct.Mutex.html
105 /// [`RwLock`]: struct.RwLock.html
106 /// [`TryLockResult`]: type.TryLockResult.html
107 /// [`try_lock`]: struct.Mutex.html#method.try_lock
108 /// [`try_read`]: struct.RwLock.html#method.try_read
109 /// [`try_write`]: struct.RwLock.html#method.try_write
110 #[stable(feature = "rust1", since = "1.0.0")]
111 pub enum TryLockError<T> {
112 /// The lock could not be acquired because another thread failed while holding
114 #[stable(feature = "rust1", since = "1.0.0")]
115 Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
116 /// The lock could not be acquired at this time because the operation would
118 #[stable(feature = "rust1", since = "1.0.0")]
122 /// A type alias for the result of a lock method which can be poisoned.
124 /// The [`Ok`] variant of this result indicates that the primitive was not
125 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
126 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
127 /// the associated guard, and it can be acquired through the [`into_inner`]
130 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
131 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
132 /// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
133 #[stable(feature = "rust1", since = "1.0.0")]
134 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
136 /// A type alias for the result of a nonblocking locking method.
138 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
139 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
140 /// have been acquired for other reasons.
142 /// [`LockResult`]: ../../std/sync/type.LockResult.html
143 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T> fmt::Debug for PoisonError<T> {
149 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
150 "PoisonError { inner: .. }".fmt(f)
154 #[stable(feature = "rust1", since = "1.0.0")]
155 impl<T> fmt::Display for PoisonError<T> {
156 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157 "poisoned lock: another task failed inside".fmt(f)
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl<T> Error for PoisonError<T> {
163 fn description(&self) -> &str {
164 "poisoned lock: another task failed inside"
168 impl<T> PoisonError<T> {
169 /// Creates a `PoisonError`.
171 /// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
173 /// [`Mutex::lock`]: ../../std/sync/struct.Mutex.html#method.lock
174 /// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
175 #[stable(feature = "sync_poison", since = "1.2.0")]
176 pub fn new(guard: T) -> PoisonError<T> {
177 PoisonError { guard: guard }
180 /// Consumes this error indicating that a lock is poisoned, returning the
181 /// underlying guard to allow access regardless.
186 /// use std::collections::HashSet;
187 /// use std::sync::{Arc, Mutex};
190 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
192 /// // poison the mutex
193 /// let c_mutex = mutex.clone();
194 /// let _ = thread::spawn(move || {
195 /// let mut data = c_mutex.lock().unwrap();
200 /// let p_err = mutex.lock().unwrap_err();
201 /// let data = p_err.into_inner();
202 /// println!("recovered {} items", data.len());
204 #[stable(feature = "sync_poison", since = "1.2.0")]
205 pub fn into_inner(self) -> T { self.guard }
207 /// Reaches into this error indicating that a lock is poisoned, returning a
208 /// reference to the underlying guard to allow access regardless.
209 #[stable(feature = "sync_poison", since = "1.2.0")]
210 pub fn get_ref(&self) -> &T { &self.guard }
212 /// Reaches into this error indicating that a lock is poisoned, returning a
213 /// mutable reference to the underlying guard to allow access regardless.
214 #[stable(feature = "sync_poison", since = "1.2.0")]
215 pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
218 #[stable(feature = "rust1", since = "1.0.0")]
219 impl<T> From<PoisonError<T>> for TryLockError<T> {
220 fn from(err: PoisonError<T>) -> TryLockError<T> {
221 TryLockError::Poisoned(err)
225 #[stable(feature = "rust1", since = "1.0.0")]
226 impl<T> fmt::Debug for TryLockError<T> {
227 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
229 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
230 TryLockError::WouldBlock => "WouldBlock".fmt(f)
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<T> fmt::Display for TryLockError<T> {
237 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
240 TryLockError::WouldBlock => "try_lock failed because the operation would block"
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl<T> Error for TryLockError<T> {
247 fn description(&self) -> &str {
249 TryLockError::Poisoned(ref p) => p.description(),
250 TryLockError::WouldBlock => "try_lock failed because the operation would block"
254 fn cause(&self) -> Option<&Error> {
256 TryLockError::Poisoned(ref p) => Some(p),
262 pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
264 where F: FnOnce(T) -> U {
267 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard)))