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 = Arc::clone(&mutex);
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);
80 /// [`Mutex`]: crate::sync::Mutex
81 /// [`RwLock`]: crate::sync::RwLock
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub struct PoisonError<T> {
87 /// An enumeration of possible errors associated with a [`TryLockResult`] which
88 /// can occur while trying to acquire a lock, from the [`try_lock`] method on a
89 /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
91 /// [`try_lock`]: crate::sync::Mutex::try_lock
92 /// [`try_read`]: crate::sync::RwLock::try_read
93 /// [`try_write`]: crate::sync::RwLock::try_write
94 /// [`Mutex`]: crate::sync::Mutex
95 /// [`RwLock`]: crate::sync::RwLock
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub enum TryLockError<T> {
98 /// The lock could not be acquired because another thread failed while holding
100 #[stable(feature = "rust1", since = "1.0.0")]
101 Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
102 /// The lock could not be acquired at this time because the operation would
104 #[stable(feature = "rust1", since = "1.0.0")]
108 /// A type alias for the result of a lock method which can be poisoned.
110 /// The [`Ok`] variant of this result indicates that the primitive was not
111 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
112 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
113 /// the associated guard, and it can be acquired through the [`into_inner`]
116 /// [`into_inner`]: PoisonError::into_inner
117 #[stable(feature = "rust1", since = "1.0.0")]
118 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
120 /// A type alias for the result of a nonblocking locking method.
122 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
123 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
124 /// have been acquired for other reasons.
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
128 #[stable(feature = "rust1", since = "1.0.0")]
129 impl<T> fmt::Debug for PoisonError<T> {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 f.debug_struct("PoisonError").finish_non_exhaustive()
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<T> fmt::Display for PoisonError<T> {
137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138 "poisoned lock: another task failed inside".fmt(f)
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<T> Error for PoisonError<T> {
145 fn description(&self) -> &str {
146 "poisoned lock: another task failed inside"
150 impl<T> PoisonError<T> {
151 /// Creates a `PoisonError`.
153 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
154 /// or [`RwLock::read`](crate::sync::RwLock::read).
155 #[stable(feature = "sync_poison", since = "1.2.0")]
156 pub fn new(guard: T) -> PoisonError<T> {
157 PoisonError { guard }
160 /// Consumes this error indicating that a lock is poisoned, returning the
161 /// underlying guard to allow access regardless.
166 /// use std::collections::HashSet;
167 /// use std::sync::{Arc, Mutex};
170 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
172 /// // poison the mutex
173 /// let c_mutex = Arc::clone(&mutex);
174 /// let _ = thread::spawn(move || {
175 /// let mut data = c_mutex.lock().unwrap();
180 /// let p_err = mutex.lock().unwrap_err();
181 /// let data = p_err.into_inner();
182 /// println!("recovered {} items", data.len());
184 #[stable(feature = "sync_poison", since = "1.2.0")]
185 pub fn into_inner(self) -> T {
189 /// Reaches into this error indicating that a lock is poisoned, returning a
190 /// reference to the underlying guard to allow access regardless.
191 #[stable(feature = "sync_poison", since = "1.2.0")]
192 pub fn get_ref(&self) -> &T {
196 /// Reaches into this error indicating that a lock is poisoned, returning a
197 /// mutable reference to the underlying guard to allow access regardless.
198 #[stable(feature = "sync_poison", since = "1.2.0")]
199 pub fn get_mut(&mut self) -> &mut T {
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T> From<PoisonError<T>> for TryLockError<T> {
206 fn from(err: PoisonError<T>) -> TryLockError<T> {
207 TryLockError::Poisoned(err)
211 #[stable(feature = "rust1", since = "1.0.0")]
212 impl<T> fmt::Debug for TryLockError<T> {
213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
216 TryLockError::WouldBlock => "WouldBlock".fmt(f),
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T> fmt::Display for TryLockError<T> {
223 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
225 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
226 TryLockError::WouldBlock => "try_lock failed because the operation would block",
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl<T> Error for TryLockError<T> {
234 #[allow(deprecated, deprecated_in_future)]
235 fn description(&self) -> &str {
237 TryLockError::Poisoned(ref p) => p.description(),
238 TryLockError::WouldBlock => "try_lock failed because the operation would block",
243 fn cause(&self) -> Option<&dyn Error> {
245 TryLockError::Poisoned(ref p) => Some(p),
251 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
257 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),