]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys_common/poison.rs
Auto merge of #69482 - lqd:poloniusup, r=nikomatsakis
[rust.git] / src / libstd / sys_common / 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
45 pub struct Guard {
46     panicking: bool,
47 }
48
49 /// A type of error which can be returned whenever a lock is acquired.
50 ///
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.
55 ///
56 /// # Examples
57 ///
58 /// ```
59 /// use std::sync::{Arc, Mutex};
60 /// use std::thread;
61 ///
62 /// let mutex = Arc::new(Mutex::new(1));
63 ///
64 /// // poison the mutex
65 /// let c_mutex = mutex.clone();
66 /// let _ = thread::spawn(move || {
67 ///     let mut data = c_mutex.lock().unwrap();
68 ///     *data = 2;
69 ///     panic!();
70 /// }).join();
71 ///
72 /// match mutex.lock() {
73 ///     Ok(_) => unreachable!(),
74 ///     Err(p_err) => {
75 ///         let data = p_err.get_ref();
76 ///         println!("recovered: {}", data);
77 ///     }
78 /// };
79 /// ```
80 ///
81 /// [`Mutex`]: ../../std/sync/struct.Mutex.html
82 /// [`RwLock`]: ../../std/sync/struct.RwLock.html
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct PoisonError<T> {
85     guard: T,
86 }
87
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`].
91 ///
92 /// [`Mutex`]: struct.Mutex.html
93 /// [`RwLock`]: struct.RwLock.html
94 /// [`TryLockResult`]: type.TryLockResult.html
95 /// [`try_lock`]: struct.Mutex.html#method.try_lock
96 /// [`try_read`]: struct.RwLock.html#method.try_read
97 /// [`try_write`]: struct.RwLock.html#method.try_write
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub enum TryLockError<T> {
100     /// The lock could not be acquired because another thread failed while holding
101     /// the lock.
102     #[stable(feature = "rust1", since = "1.0.0")]
103     Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
104     /// The lock could not be acquired at this time because the operation would
105     /// otherwise block.
106     #[stable(feature = "rust1", since = "1.0.0")]
107     WouldBlock,
108 }
109
110 /// A type alias for the result of a lock method which can be poisoned.
111 ///
112 /// The [`Ok`] variant of this result indicates that the primitive was not
113 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
114 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
115 /// the associated guard, and it can be acquired through the [`into_inner`]
116 /// method.
117 ///
118 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
119 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
120 /// [`into_inner`]: ../../std/sync/struct.PoisonError.html#method.into_inner
121 #[stable(feature = "rust1", since = "1.0.0")]
122 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
123
124 /// A type alias for the result of a nonblocking locking method.
125 ///
126 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
127 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
128 /// have been acquired for other reasons.
129 ///
130 /// [`LockResult`]: ../../std/sync/type.LockResult.html
131 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
132 #[stable(feature = "rust1", since = "1.0.0")]
133 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
134
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<T> fmt::Debug for PoisonError<T> {
137     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138         "PoisonError { inner: .. }".fmt(f)
139     }
140 }
141
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<T> fmt::Display for PoisonError<T> {
144     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145         "poisoned lock: another task failed inside".fmt(f)
146     }
147 }
148
149 #[stable(feature = "rust1", since = "1.0.0")]
150 impl<T> Error for PoisonError<T> {
151     #[allow(deprecated)]
152     fn description(&self) -> &str {
153         "poisoned lock: another task failed inside"
154     }
155 }
156
157 impl<T> PoisonError<T> {
158     /// Creates a `PoisonError`.
159     ///
160     /// This is generally created by methods like [`Mutex::lock`] or [`RwLock::read`].
161     ///
162     /// [`Mutex::lock`]: ../../std/sync/struct.Mutex.html#method.lock
163     /// [`RwLock::read`]: ../../std/sync/struct.RwLock.html#method.read
164     #[stable(feature = "sync_poison", since = "1.2.0")]
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 = mutex.clone();
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     #[stable(feature = "sync_poison", since = "1.2.0")]
194     pub fn into_inner(self) -> T {
195         self.guard
196     }
197
198     /// Reaches into this error indicating that a lock is poisoned, returning a
199     /// reference to the underlying guard to allow access regardless.
200     #[stable(feature = "sync_poison", since = "1.2.0")]
201     pub fn get_ref(&self) -> &T {
202         &self.guard
203     }
204
205     /// Reaches into this error indicating that a lock is poisoned, returning a
206     /// mutable reference to the underlying guard to allow access regardless.
207     #[stable(feature = "sync_poison", since = "1.2.0")]
208     pub fn get_mut(&mut self) -> &mut T {
209         &mut self.guard
210     }
211 }
212
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl<T> From<PoisonError<T>> for TryLockError<T> {
215     fn from(err: PoisonError<T>) -> TryLockError<T> {
216         TryLockError::Poisoned(err)
217     }
218 }
219
220 #[stable(feature = "rust1", since = "1.0.0")]
221 impl<T> fmt::Debug for TryLockError<T> {
222     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223         match *self {
224             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
225             TryLockError::WouldBlock => "WouldBlock".fmt(f),
226         }
227     }
228 }
229
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<T> fmt::Display for TryLockError<T> {
232     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233         match *self {
234             TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
235             TryLockError::WouldBlock => "try_lock failed because the operation would block",
236         }
237         .fmt(f)
238     }
239 }
240
241 #[stable(feature = "rust1", since = "1.0.0")]
242 impl<T> Error for TryLockError<T> {
243     #[allow(deprecated, deprecated_in_future)]
244     fn description(&self) -> &str {
245         match *self {
246             TryLockError::Poisoned(ref p) => p.description(),
247             TryLockError::WouldBlock => "try_lock failed because the operation would block",
248         }
249     }
250
251     #[allow(deprecated)]
252     fn cause(&self) -> Option<&dyn Error> {
253         match *self {
254             TryLockError::Poisoned(ref p) => Some(p),
255             _ => None,
256         }
257     }
258 }
259
260 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
261 where
262     F: FnOnce(T) -> U,
263 {
264     match result {
265         Ok(t) => Ok(f(t)),
266         Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
267     }
268 }