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)
46 self.failed.store(false, Ordering::Relaxed)
54 /// A type of error which can be returned whenever a lock is acquired.
56 /// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
57 /// is held. The precise semantics for when a lock is poisoned is documented on
58 /// each lock, but once a lock is poisoned then all future acquisitions will
59 /// return this error.
64 /// use std::sync::{Arc, Mutex};
67 /// let mutex = Arc::new(Mutex::new(1));
69 /// // poison the mutex
70 /// let c_mutex = Arc::clone(&mutex);
71 /// let _ = thread::spawn(move || {
72 /// let mut data = c_mutex.lock().unwrap();
77 /// match mutex.lock() {
78 /// Ok(_) => unreachable!(),
80 /// let data = p_err.get_ref();
81 /// println!("recovered: {data}");
85 /// [`Mutex`]: crate::sync::Mutex
86 /// [`RwLock`]: crate::sync::RwLock
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub struct PoisonError<T> {
92 /// An enumeration of possible errors associated with a [`TryLockResult`] which
93 /// can occur while trying to acquire a lock, from the [`try_lock`] method on a
94 /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
96 /// [`try_lock`]: crate::sync::Mutex::try_lock
97 /// [`try_read`]: crate::sync::RwLock::try_read
98 /// [`try_write`]: crate::sync::RwLock::try_write
99 /// [`Mutex`]: crate::sync::Mutex
100 /// [`RwLock`]: crate::sync::RwLock
101 #[stable(feature = "rust1", since = "1.0.0")]
102 pub enum TryLockError<T> {
103 /// The lock could not be acquired because another thread failed while holding
105 #[stable(feature = "rust1", since = "1.0.0")]
106 Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
107 /// The lock could not be acquired at this time because the operation would
109 #[stable(feature = "rust1", since = "1.0.0")]
113 /// A type alias for the result of a lock method which can be poisoned.
115 /// The [`Ok`] variant of this result indicates that the primitive was not
116 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
117 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
118 /// the associated guard, and it can be acquired through the [`into_inner`]
121 /// [`into_inner`]: PoisonError::into_inner
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
125 /// A type alias for the result of a nonblocking locking method.
127 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
128 /// necessarily hold the associated guard in the [`Err`] type as the lock might not
129 /// have been acquired for other reasons.
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
133 #[stable(feature = "rust1", since = "1.0.0")]
134 impl<T> fmt::Debug for PoisonError<T> {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 f.debug_struct("PoisonError").finish_non_exhaustive()
140 #[stable(feature = "rust1", since = "1.0.0")]
141 impl<T> fmt::Display for PoisonError<T> {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 "poisoned lock: another task failed inside".fmt(f)
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T> Error for PoisonError<T> {
150 fn description(&self) -> &str {
151 "poisoned lock: another task failed inside"
155 impl<T> PoisonError<T> {
156 /// Creates a `PoisonError`.
158 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
159 /// or [`RwLock::read`](crate::sync::RwLock::read).
160 #[stable(feature = "sync_poison", since = "1.2.0")]
161 pub fn new(guard: T) -> PoisonError<T> {
162 PoisonError { guard }
165 /// Consumes this error indicating that a lock is poisoned, returning the
166 /// underlying guard to allow access regardless.
171 /// use std::collections::HashSet;
172 /// use std::sync::{Arc, Mutex};
175 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
177 /// // poison the mutex
178 /// let c_mutex = Arc::clone(&mutex);
179 /// let _ = thread::spawn(move || {
180 /// let mut data = c_mutex.lock().unwrap();
185 /// let p_err = mutex.lock().unwrap_err();
186 /// let data = p_err.into_inner();
187 /// println!("recovered {} items", data.len());
189 #[stable(feature = "sync_poison", since = "1.2.0")]
190 pub fn into_inner(self) -> T {
194 /// Reaches into this error indicating that a lock is poisoned, returning a
195 /// reference to the underlying guard to allow access regardless.
196 #[stable(feature = "sync_poison", since = "1.2.0")]
197 pub fn get_ref(&self) -> &T {
201 /// Reaches into this error indicating that a lock is poisoned, returning a
202 /// mutable reference to the underlying guard to allow access regardless.
203 #[stable(feature = "sync_poison", since = "1.2.0")]
204 pub fn get_mut(&mut self) -> &mut T {
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<T> From<PoisonError<T>> for TryLockError<T> {
211 fn from(err: PoisonError<T>) -> TryLockError<T> {
212 TryLockError::Poisoned(err)
216 #[stable(feature = "rust1", since = "1.0.0")]
217 impl<T> fmt::Debug for TryLockError<T> {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
221 TryLockError::WouldBlock => "WouldBlock".fmt(f),
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<T> fmt::Display for TryLockError<T> {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
230 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
231 TryLockError::WouldBlock => "try_lock failed because the operation would block",
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl<T> Error for TryLockError<T> {
239 #[allow(deprecated, deprecated_in_future)]
240 fn description(&self) -> &str {
242 TryLockError::Poisoned(ref p) => p.description(),
243 TryLockError::WouldBlock => "try_lock failed because the operation would block",
248 fn cause(&self) -> Option<&dyn Error> {
250 TryLockError::Poisoned(ref p) => Some(p),
256 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
262 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),