]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/poison.rs
Auto merge of #76128 - poliorcetics:doc-use-arc-clone, r=KodrAus
[rust.git] / library / std / src / 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 #[allow(unused_imports)] // for intra-doc links
7 use crate::sync::{Mutex, RwLock};
8
9 pub struct Flag {
10     failed: AtomicBool,
11 }
12
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.
16 //
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.
20 //
21 // As a result, if it matters, we should see the correct value for `failed` in
22 // all cases.
23
24 impl Flag {
25     pub const fn new() -> Flag {
26         Flag { failed: AtomicBool::new(false) }
27     }
28
29     #[inline]
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) }
33     }
34
35     #[inline]
36     pub fn done(&self, guard: &Guard) {
37         if !guard.panicking && thread::panicking() {
38             self.failed.store(true, Ordering::Relaxed);
39         }
40     }
41
42     #[inline]
43     pub fn get(&self) -> bool {
44         self.failed.load(Ordering::Relaxed)
45     }
46 }
47
48 pub struct Guard {
49     panicking: bool,
50 }
51
52 /// A type of error which can be returned whenever a lock is acquired.
53 ///
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.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// use std::sync::{Arc, Mutex};
63 /// use std::thread;
64 ///
65 /// let mutex = Arc::new(Mutex::new(1));
66 ///
67 /// // poison the mutex
68 /// let c_mutex = Arc::clone(&mutex);
69 /// let _ = thread::spawn(move || {
70 ///     let mut data = c_mutex.lock().unwrap();
71 ///     *data = 2;
72 ///     panic!();
73 /// }).join();
74 ///
75 /// match mutex.lock() {
76 ///     Ok(_) => unreachable!(),
77 ///     Err(p_err) => {
78 ///         let data = p_err.get_ref();
79 ///         println!("recovered: {}", data);
80 ///     }
81 /// };
82 /// ```
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 /// [`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
98     /// the lock.
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
102     /// otherwise block.
103     #[stable(feature = "rust1", since = "1.0.0")]
104     WouldBlock,
105 }
106
107 /// A type alias for the result of a lock method which can be poisoned.
108 ///
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`]
113 /// method.
114 ///
115 /// [`into_inner`]: PoisonError::into_inner
116 #[stable(feature = "rust1", since = "1.0.0")]
117 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
118
119 /// A type alias for the result of a nonblocking locking method.
120 ///
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>>;
126
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)
131     }
132 }
133
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)
138     }
139 }
140
141 #[stable(feature = "rust1", since = "1.0.0")]
142 impl<T> Error for PoisonError<T> {
143     #[allow(deprecated)]
144     fn description(&self) -> &str {
145         "poisoned lock: another task failed inside"
146     }
147 }
148
149 impl<T> PoisonError<T> {
150     /// Creates a `PoisonError`.
151     ///
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 }
156     }
157
158     /// Consumes this error indicating that a lock is poisoned, returning the
159     /// underlying guard to allow access regardless.
160     ///
161     /// # Examples
162     ///
163     /// ```
164     /// use std::collections::HashSet;
165     /// use std::sync::{Arc, Mutex};
166     /// use std::thread;
167     ///
168     /// let mutex = Arc::new(Mutex::new(HashSet::new()));
169     ///
170     /// // poison the mutex
171     /// let c_mutex = Arc::clone(&mutex);
172     /// let _ = thread::spawn(move || {
173     ///     let mut data = c_mutex.lock().unwrap();
174     ///     data.insert(10);
175     ///     panic!();
176     /// }).join();
177     ///
178     /// let p_err = mutex.lock().unwrap_err();
179     /// let data = p_err.into_inner();
180     /// println!("recovered {} items", data.len());
181     /// ```
182     #[stable(feature = "sync_poison", since = "1.2.0")]
183     pub fn into_inner(self) -> T {
184         self.guard
185     }
186
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 {
191         &self.guard
192     }
193
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 {
198         &mut self.guard
199     }
200 }
201
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)
206     }
207 }
208
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 {
212         match *self {
213             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
214             TryLockError::WouldBlock => "WouldBlock".fmt(f),
215         }
216     }
217 }
218
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 {
222         match *self {
223             TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
224             TryLockError::WouldBlock => "try_lock failed because the operation would block",
225         }
226         .fmt(f)
227     }
228 }
229
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 {
234         match *self {
235             TryLockError::Poisoned(ref p) => p.description(),
236             TryLockError::WouldBlock => "try_lock failed because the operation would block",
237         }
238     }
239
240     #[allow(deprecated)]
241     fn cause(&self) -> Option<&dyn Error> {
242         match *self {
243             TryLockError::Poisoned(ref p) => Some(p),
244             _ => None,
245         }
246     }
247 }
248
249 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
250 where
251     F: FnOnce(T) -> U,
252 {
253     match result {
254         Ok(t) => Ok(f(t)),
255         Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
256     }
257 }