]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/poison.rs
Rollup merge of #97358 - GuillaumeGomez:update-minifier, r=Dylan-DPC
[rust.git] / library / std / src / sync / poison.rs
1 use crate::error::Error;
2 use crate::fmt;
3 use crate::sync::atomic::{AtomicBool, Ordering};
4 use crate::thread;
5
6 pub struct Flag {
7     failed: AtomicBool,
8 }
9
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.
13 //
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.
17 //
18 // As a result, if it matters, we should see the correct value for `failed` in
19 // all cases.
20
21 impl Flag {
22     pub const fn new() -> Flag {
23         Flag { failed: AtomicBool::new(false) }
24     }
25
26     #[inline]
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) }
30     }
31
32     #[inline]
33     pub fn done(&self, guard: &Guard) {
34         if !guard.panicking && thread::panicking() {
35             self.failed.store(true, Ordering::Relaxed);
36         }
37     }
38
39     #[inline]
40     pub fn get(&self) -> bool {
41         self.failed.load(Ordering::Relaxed)
42     }
43
44     #[inline]
45     pub fn clear(&self) {
46         self.failed.store(false, Ordering::Relaxed)
47     }
48 }
49
50 pub struct Guard {
51     panicking: bool,
52 }
53
54 /// A type of error which can be returned whenever a lock is acquired.
55 ///
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.
60 ///
61 /// # Examples
62 ///
63 /// ```
64 /// use std::sync::{Arc, Mutex};
65 /// use std::thread;
66 ///
67 /// let mutex = Arc::new(Mutex::new(1));
68 ///
69 /// // poison the mutex
70 /// let c_mutex = Arc::clone(&mutex);
71 /// let _ = thread::spawn(move || {
72 ///     let mut data = c_mutex.lock().unwrap();
73 ///     *data = 2;
74 ///     panic!();
75 /// }).join();
76 ///
77 /// match mutex.lock() {
78 ///     Ok(_) => unreachable!(),
79 ///     Err(p_err) => {
80 ///         let data = p_err.get_ref();
81 ///         println!("recovered: {data}");
82 ///     }
83 /// };
84 /// ```
85 /// [`Mutex`]: crate::sync::Mutex
86 /// [`RwLock`]: crate::sync::RwLock
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub struct PoisonError<T> {
89     guard: T,
90 }
91
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`].
95 ///
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
104     /// the lock.
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
108     /// otherwise block.
109     #[stable(feature = "rust1", since = "1.0.0")]
110     WouldBlock,
111 }
112
113 /// A type alias for the result of a lock method which can be poisoned.
114 ///
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`]
119 /// method.
120 ///
121 /// [`into_inner`]: PoisonError::into_inner
122 #[stable(feature = "rust1", since = "1.0.0")]
123 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
124
125 /// A type alias for the result of a nonblocking locking method.
126 ///
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>>;
132
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()
137     }
138 }
139
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)
144     }
145 }
146
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T> Error for PoisonError<T> {
149     #[allow(deprecated)]
150     fn description(&self) -> &str {
151         "poisoned lock: another task failed inside"
152     }
153 }
154
155 impl<T> PoisonError<T> {
156     /// Creates a `PoisonError`.
157     ///
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 }
163     }
164
165     /// Consumes this error indicating that a lock is poisoned, returning the
166     /// underlying guard to allow access regardless.
167     ///
168     /// # Examples
169     ///
170     /// ```
171     /// use std::collections::HashSet;
172     /// use std::sync::{Arc, Mutex};
173     /// use std::thread;
174     ///
175     /// let mutex = Arc::new(Mutex::new(HashSet::new()));
176     ///
177     /// // poison the mutex
178     /// let c_mutex = Arc::clone(&mutex);
179     /// let _ = thread::spawn(move || {
180     ///     let mut data = c_mutex.lock().unwrap();
181     ///     data.insert(10);
182     ///     panic!();
183     /// }).join();
184     ///
185     /// let p_err = mutex.lock().unwrap_err();
186     /// let data = p_err.into_inner();
187     /// println!("recovered {} items", data.len());
188     /// ```
189     #[stable(feature = "sync_poison", since = "1.2.0")]
190     pub fn into_inner(self) -> T {
191         self.guard
192     }
193
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 {
198         &self.guard
199     }
200
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 {
205         &mut self.guard
206     }
207 }
208
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)
213     }
214 }
215
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 {
219         match *self {
220             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
221             TryLockError::WouldBlock => "WouldBlock".fmt(f),
222         }
223     }
224 }
225
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 {
229         match *self {
230             TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
231             TryLockError::WouldBlock => "try_lock failed because the operation would block",
232         }
233         .fmt(f)
234     }
235 }
236
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 {
241         match *self {
242             TryLockError::Poisoned(ref p) => p.description(),
243             TryLockError::WouldBlock => "try_lock failed because the operation would block",
244         }
245     }
246
247     #[allow(deprecated)]
248     fn cause(&self) -> Option<&dyn Error> {
249         match *self {
250             TryLockError::Poisoned(ref p) => Some(p),
251             _ => None,
252         }
253     }
254 }
255
256 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
257 where
258     F: FnOnce(T) -> U,
259 {
260     match result {
261         Ok(t) => Ok(f(t)),
262         Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
263     }
264 }