1 use crate::error::Error;
3 use crate::sync::atomic::{AtomicBool, Ordering};
10 // Note that the Ordering uses to access the `failed` field of `Flag` below is
11 // always `Relaxed`, and that's because this isn't actually protecting any data,
12 // it's just a flag whether we've panicked or not.
14 // The actual location that this matters is when a mutex is **locked** which is
15 // where we have external synchronization ensuring that we see memory
16 // reads/writes to this flag.
18 // As a result, if it matters, we should see the correct value for `failed` in
22 pub const fn new() -> Flag {
23 Flag { failed: AtomicBool::new(false) }
27 pub fn borrow(&self) -> LockResult<Guard> {
28 let ret = Guard { panicking: thread::panicking() };
29 if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
33 pub fn done(&self, guard: &Guard) {
34 if !guard.panicking && thread::panicking() {
35 self.failed.store(true, Ordering::Relaxed);
40 pub fn get(&self) -> bool {
41 self.failed.load(Ordering::Relaxed)
49 /// A type of error which can be returned whenever a lock is acquired.
51 /// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
52 /// is held. The precise semantics for when a lock is poisoned is documented on
53 /// each lock, but once a lock is poisoned then all future acquisitions will
54 /// return this error.
59 /// use std::sync::{Arc, Mutex};
62 /// let mutex = Arc::new(Mutex::new(1));
64 /// // poison the mutex
65 /// let c_mutex = mutex.clone();
66 /// let _ = thread::spawn(move || {
67 /// let mut data = c_mutex.lock().unwrap();
72 /// match mutex.lock() {
73 /// Ok(_) => unreachable!(),
75 /// let data = p_err.get_ref();
76 /// println!("recovered: {}", data);
81 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
82 /// [`RwLock`]: ../../std/sync/struct.RwLock.html
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct PoisonError<T> {
88 /// An enumeration of possible errors associated with a [`TryLockResult`] which
89 /// can occur while trying to acquire a lock, from the [`try_lock`] method on a
90 /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
92 /// [`Mutex`]: struct.Mutex.html
93 /// [`RwLock`]: struct.RwLock.html
94 /// [`TryLockResult`]: type.TryLockResult.html
95 /// [`try_lock`]: struct.Mutex.html#method.try_lock
96 /// [`try_read`]: struct.RwLock.html#method.try_read
97 /// [`try_write`]: struct.RwLock.html#method.try_write
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub enum TryLockError<T> {
100 /// The lock could not be acquired because another thread failed while holding
102 #[stable(feature = "rust1", since = "1.0.0")]
103 Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
104 /// The lock could not be acquired at this time because the operation would
106 #[stable(feature = "rust1", since = "1.0.0")]
110 /// A type alias for the result of a lock method which can be poisoned.
112 /// The [`Ok`] variant of this result indicates that the primitive was not
113 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
114 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
115 /// the associated guard, and it can be acquired through the [`into_inner`]
118 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
119 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
120 /// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
124 /// A type alias for the result of a nonblocking locking method.
126 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
127 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
128 /// have been acquired for other reasons.
130 /// [`LockResult`]: ../../std/sync/type.LockResult.html
131 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<T> fmt::Debug for PoisonError<T> {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 "PoisonError { inner: .. }".fmt(f)
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<T> fmt::Display for PoisonError<T> {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 "poisoned lock: another task failed inside".fmt(f)
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl<T> Error for PoisonError<T> {
152 fn description(&self) -> &str {
153 "poisoned lock: another task failed inside"
157 impl<T> PoisonError<T> {
158 /// Creates a `PoisonError`.
160 /// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
162 /// [`Mutex::lock`]: ../../std/sync/struct.Mutex.html#method.lock
163 /// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
164 #[stable(feature = "sync_poison", since = "1.2.0")]
165 pub fn new(guard: T) -> PoisonError<T> {
166 PoisonError { guard }
169 /// Consumes this error indicating that a lock is poisoned, returning the
170 /// underlying guard to allow access regardless.
175 /// use std::collections::HashSet;
176 /// use std::sync::{Arc, Mutex};
179 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
181 /// // poison the mutex
182 /// let c_mutex = mutex.clone();
183 /// let _ = thread::spawn(move || {
184 /// let mut data = c_mutex.lock().unwrap();
189 /// let p_err = mutex.lock().unwrap_err();
190 /// let data = p_err.into_inner();
191 /// println!("recovered {} items", data.len());
193 #[stable(feature = "sync_poison", since = "1.2.0")]
194 pub fn into_inner(self) -> T {
198 /// Reaches into this error indicating that a lock is poisoned, returning a
199 /// reference to the underlying guard to allow access regardless.
200 #[stable(feature = "sync_poison", since = "1.2.0")]
201 pub fn get_ref(&self) -> &T {
205 /// Reaches into this error indicating that a lock is poisoned, returning a
206 /// mutable reference to the underlying guard to allow access regardless.
207 #[stable(feature = "sync_poison", since = "1.2.0")]
208 pub fn get_mut(&mut self) -> &mut T {
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl<T> From<PoisonError<T>> for TryLockError<T> {
215 fn from(err: PoisonError<T>) -> TryLockError<T> {
216 TryLockError::Poisoned(err)
220 #[stable(feature = "rust1", since = "1.0.0")]
221 impl<T> fmt::Debug for TryLockError<T> {
222 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
225 TryLockError::WouldBlock => "WouldBlock".fmt(f),
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<T> fmt::Display for TryLockError<T> {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
235 TryLockError::WouldBlock => "try_lock failed because the operation would block",
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<T> Error for TryLockError<T> {
243 #[allow(deprecated, deprecated_in_future)]
244 fn description(&self) -> &str {
246 TryLockError::Poisoned(ref p) => p.description(),
247 TryLockError::WouldBlock => "try_lock failed because the operation would block",
252 fn cause(&self) -> Option<&dyn Error> {
254 TryLockError::Poisoned(ref p) => Some(p),
260 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
266 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),