1 use crate::error::Error;
3 use crate::sync::atomic::{AtomicBool, Ordering};
6 #[allow(unused_imports)] // for intra-doc links
7 use crate::sync::{Mutex, RwLock};
13 // Note that the Ordering uses to access the `failed` field of `Flag` below is
14 // always `Relaxed`, and that's because this isn't actually protecting any data,
15 // it's just a flag whether we've panicked or not.
17 // The actual location that this matters is when a mutex is **locked** which is
18 // where we have external synchronization ensuring that we see memory
19 // reads/writes to this flag.
21 // As a result, if it matters, we should see the correct value for `failed` in
25 pub const fn new() -> Flag {
26 Flag { failed: AtomicBool::new(false) }
30 pub fn borrow(&self) -> LockResult<Guard> {
31 let ret = Guard { panicking: thread::panicking() };
32 if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
36 pub fn done(&self, guard: &Guard) {
37 if !guard.panicking && thread::panicking() {
38 self.failed.store(true, Ordering::Relaxed);
43 pub fn get(&self) -> bool {
44 self.failed.load(Ordering::Relaxed)
52 /// A type of error which can be returned whenever a lock is acquired.
54 /// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
55 /// is held. The precise semantics for when a lock is poisoned is documented on
56 /// each lock, but once a lock is poisoned then all future acquisitions will
57 /// return this error.
62 /// use std::sync::{Arc, Mutex};
65 /// let mutex = Arc::new(Mutex::new(1));
67 /// // poison the mutex
68 /// let c_mutex = Arc::clone(&mutex);
69 /// let _ = thread::spawn(move || {
70 /// let mut data = c_mutex.lock().unwrap();
75 /// match mutex.lock() {
76 /// Ok(_) => unreachable!(),
78 /// let data = p_err.get_ref();
79 /// println!("recovered: {}", data);
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 /// [`try_lock`]: Mutex::try_lock
93 /// [`try_read`]: RwLock::try_read
94 /// [`try_write`]: RwLock::try_write
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub enum TryLockError<T> {
97 /// The lock could not be acquired because another thread failed while holding
99 #[stable(feature = "rust1", since = "1.0.0")]
100 Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
101 /// The lock could not be acquired at this time because the operation would
103 #[stable(feature = "rust1", since = "1.0.0")]
107 /// A type alias for the result of a lock method which can be poisoned.
109 /// The [`Ok`] variant of this result indicates that the primitive was not
110 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
111 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
112 /// the associated guard, and it can be acquired through the [`into_inner`]
115 /// [`into_inner`]: PoisonError::into_inner
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
119 /// A type alias for the result of a nonblocking locking method.
121 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
122 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
123 /// have been acquired for other reasons.
124 #[stable(feature = "rust1", since = "1.0.0")]
125 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
127 #[stable(feature = "rust1", since = "1.0.0")]
128 impl<T> fmt::Debug for PoisonError<T> {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 "PoisonError { inner: .. }".fmt(f)
134 #[stable(feature = "rust1", since = "1.0.0")]
135 impl<T> fmt::Display for PoisonError<T> {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 "poisoned lock: another task failed inside".fmt(f)
141 #[stable(feature = "rust1", since = "1.0.0")]
142 impl<T> Error for PoisonError<T> {
144 fn description(&self) -> &str {
145 "poisoned lock: another task failed inside"
149 impl<T> PoisonError<T> {
150 /// Creates a `PoisonError`.
152 /// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
153 #[stable(feature = "sync_poison", since = "1.2.0")]
154 pub fn new(guard: T) -> PoisonError<T> {
155 PoisonError { guard }
158 /// Consumes this error indicating that a lock is poisoned, returning the
159 /// underlying guard to allow access regardless.
164 /// use std::collections::HashSet;
165 /// use std::sync::{Arc, Mutex};
168 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
170 /// // poison the mutex
171 /// let c_mutex = Arc::clone(&mutex);
172 /// let _ = thread::spawn(move || {
173 /// let mut data = c_mutex.lock().unwrap();
178 /// let p_err = mutex.lock().unwrap_err();
179 /// let data = p_err.into_inner();
180 /// println!("recovered {} items", data.len());
182 #[stable(feature = "sync_poison", since = "1.2.0")]
183 pub fn into_inner(self) -> T {
187 /// Reaches into this error indicating that a lock is poisoned, returning a
188 /// reference to the underlying guard to allow access regardless.
189 #[stable(feature = "sync_poison", since = "1.2.0")]
190 pub fn get_ref(&self) -> &T {
194 /// Reaches into this error indicating that a lock is poisoned, returning a
195 /// mutable reference to the underlying guard to allow access regardless.
196 #[stable(feature = "sync_poison", since = "1.2.0")]
197 pub fn get_mut(&mut self) -> &mut T {
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<T> From<PoisonError<T>> for TryLockError<T> {
204 fn from(err: PoisonError<T>) -> TryLockError<T> {
205 TryLockError::Poisoned(err)
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<T> fmt::Debug for TryLockError<T> {
211 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
214 TryLockError::WouldBlock => "WouldBlock".fmt(f),
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl<T> fmt::Display for TryLockError<T> {
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
224 TryLockError::WouldBlock => "try_lock failed because the operation would block",
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<T> Error for TryLockError<T> {
232 #[allow(deprecated, deprecated_in_future)]
233 fn description(&self) -> &str {
235 TryLockError::Poisoned(ref p) => p.description(),
236 TryLockError::WouldBlock => "try_lock failed because the operation would block",
241 fn cause(&self) -> Option<&dyn Error> {
243 TryLockError::Poisoned(ref p) => Some(p),
249 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
255 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),