k_lock/poison.rs
1// borrowed from rust std::sync
2
3use std::error::Error;
4use std::fmt;
5use std::sync::atomic::{AtomicBool, Ordering};
6use std::thread;
7
8pub struct Flag {
9 failed: AtomicBool,
10}
11
12// Note that the Ordering uses to access the `failed` field of `Flag` below is
13// always `Relaxed`, and that's because this isn't actually protecting any data,
14// it's just a flag whether we've panicked or not.
15//
16// The actual location that this matters is when a mutex is **locked** which is
17// where we have external synchronization ensuring that we see memory
18// reads/writes to this flag.
19//
20// As a result, if it matters, we should see the correct value for `failed` in
21// all cases.
22
23impl Flag {
24 #[inline]
25 pub const fn new() -> Flag {
26 Flag {
27 failed: AtomicBool::new(false),
28 }
29 }
30
31 /// Check the flag for an unguarded borrow, where we only care about existing poison.
32 #[inline]
33 pub fn borrow(&self) -> LockResult<()> {
34 if self.get() {
35 Err(PoisonError::new(()))
36 } else {
37 Ok(())
38 }
39 }
40
41 /// Check the flag for a guarded borrow, where we may also set poison when `done`.
42 #[inline]
43 pub fn guard(&self) -> LockResult<Guard> {
44 let ret = Guard {
45 panicking: thread::panicking(),
46 };
47 if self.get() {
48 Err(PoisonError::new(ret))
49 } else {
50 Ok(ret)
51 }
52 }
53
54 #[inline]
55 pub fn done(&self, guard: &Guard) {
56 if !guard.panicking && thread::panicking() {
57 self.failed.store(true, Ordering::Relaxed);
58 }
59 }
60
61 #[inline]
62 pub fn get(&self) -> bool {
63 self.failed.load(Ordering::Relaxed)
64 }
65}
66
67pub struct Guard {
68 panicking: bool,
69}
70
71/// A type of error which can be returned whenever a lock is acquired.
72///
73/// [`Mutex`]es are poisoned whenever a thread fails while the lock
74/// is held. Once a lock is poisoned then all future acquisitions will
75/// return this error.
76///
77/// # Examples
78///
79/// ```
80/// use std::sync::{Arc, Mutex};
81/// use std::thread;
82///
83/// let mutex = Arc::new(Mutex::new(1));
84///
85/// // poison the mutex
86/// let c_mutex = Arc::clone(&mutex);
87/// let _ = thread::spawn(move || {
88/// let mut data = c_mutex.lock().unwrap();
89/// *data = 2;
90/// panic!();
91/// }).join();
92///
93/// match mutex.lock() {
94/// Ok(_) => unreachable!(),
95/// Err(p_err) => {
96/// let data = p_err.get_ref();
97/// println!("recovered: {data}");
98/// }
99/// };
100/// ```
101pub struct PoisonError<T> {
102 guard: T,
103}
104
105/// An enumeration of possible errors associated with a [`TryLockResult`] which
106/// can occur while trying to acquire a lock, from the [`try_lock`] method on a
107/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
108///
109/// [`try_lock`]: crate::sync::Mutex::try_lock
110/// [`try_read`]: crate::sync::RwLock::try_read
111/// [`try_write`]: crate::sync::RwLock::try_write
112/// [`Mutex`]: crate::sync::Mutex
113/// [`RwLock`]: crate::sync::RwLock
114pub enum TryLockError<T> {
115 /// The lock could not be acquired because another thread failed while holding
116 /// the lock.
117 Poisoned(PoisonError<T>),
118 /// The lock could not be acquired at this time because the operation would
119 /// otherwise block.
120 WouldBlock,
121}
122
123/// A type alias for the result of a lock method which can be poisoned.
124///
125/// The [`Ok`] variant of this result indicates that the primitive was not
126/// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
127/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
128/// the associated guard, and it can be acquired through the [`into_inner`]
129/// method.
130///
131/// [`into_inner`]: PoisonError::into_inner
132pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
133
134/// A type alias for the result of a nonblocking locking method.
135///
136/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
137/// necessarily hold the associated guard in the [`Err`] type as the lock might not
138/// have been acquired for other reasons.
139pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
140
141impl<T> fmt::Debug for PoisonError<T> {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 f.debug_struct("PoisonError").finish_non_exhaustive()
144 }
145}
146
147impl<T> fmt::Display for PoisonError<T> {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 "poisoned lock: another task failed inside".fmt(f)
150 }
151}
152
153impl<T> Error for PoisonError<T> {
154 #[allow(deprecated)]
155 fn description(&self) -> &str {
156 "poisoned lock: another task failed inside"
157 }
158}
159
160impl<T> PoisonError<T> {
161 /// Creates a `PoisonError`.
162 ///
163 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
164 /// or [`RwLock::read`](crate::sync::RwLock::read).
165 pub fn new(guard: T) -> PoisonError<T> {
166 PoisonError { guard }
167 }
168
169 /// Consumes this error indicating that a lock is poisoned, returning the
170 /// underlying guard to allow access regardless.
171 ///
172 /// # Examples
173 ///
174 /// ```
175 /// use std::collections::HashSet;
176 /// use std::sync::{Arc, Mutex};
177 /// use std::thread;
178 ///
179 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
180 ///
181 /// // poison the mutex
182 /// let c_mutex = Arc::clone(&mutex);
183 /// let _ = thread::spawn(move || {
184 /// let mut data = c_mutex.lock().unwrap();
185 /// data.insert(10);
186 /// panic!();
187 /// }).join();
188 ///
189 /// let p_err = mutex.lock().unwrap_err();
190 /// let data = p_err.into_inner();
191 /// println!("recovered {} items", data.len());
192 /// ```
193 pub fn into_inner(self) -> T {
194 self.guard
195 }
196
197 /// Reaches into this error indicating that a lock is poisoned, returning a
198 /// reference to the underlying guard to allow access regardless.
199 pub fn get_ref(&self) -> &T {
200 &self.guard
201 }
202
203 /// Reaches into this error indicating that a lock is poisoned, returning a
204 /// mutable reference to the underlying guard to allow access regardless.
205 pub fn get_mut(&mut self) -> &mut T {
206 &mut self.guard
207 }
208}
209
210impl<T> From<PoisonError<T>> for TryLockError<T> {
211 fn from(err: PoisonError<T>) -> TryLockError<T> {
212 TryLockError::Poisoned(err)
213 }
214}
215
216impl<T> fmt::Debug for TryLockError<T> {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 match *self {
219 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
220 TryLockError::WouldBlock => "WouldBlock".fmt(f),
221 }
222 }
223}
224
225impl<T> fmt::Display for TryLockError<T> {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 match *self {
228 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
229 TryLockError::WouldBlock => "try_lock failed because the operation would block",
230 }
231 .fmt(f)
232 }
233}
234
235impl<T> Error for TryLockError<T> {
236 #[allow(deprecated, deprecated_in_future)]
237 fn description(&self) -> &str {
238 match *self {
239 TryLockError::Poisoned(ref p) => p.description(),
240 TryLockError::WouldBlock => "try_lock failed because the operation would block",
241 }
242 }
243
244 #[allow(deprecated)]
245 fn cause(&self) -> Option<&dyn Error> {
246 match *self {
247 TryLockError::Poisoned(ref p) => Some(p),
248 _ => None,
249 }
250 }
251}
252
253pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
254where
255 F: FnOnce(T) -> U,
256{
257 match result {
258 Ok(t) => Ok(f(t)),
259 Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
260 }
261}