]> git.lizzy.rs Git - rust.git/blob - library/std/src/sync/poison.rs
Auto merge of #83386 - mark-i-m:stabilize-pat2015, r=nikomatsakis
[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
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 = Arc::clone(&mutex);
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 /// [`Mutex`]: crate::sync::Mutex
81 /// [`RwLock`]: crate::sync::RwLock
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub struct PoisonError<T> {
84     guard: T,
85 }
86
87 /// An enumeration of possible errors associated with a [`TryLockResult`] which
88 /// can occur while trying to acquire a lock, from the [`try_lock`] method on a
89 /// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
90 ///
91 /// [`try_lock`]: crate::sync::Mutex::try_lock
92 /// [`try_read`]: crate::sync::RwLock::try_read
93 /// [`try_write`]: crate::sync::RwLock::try_write
94 /// [`Mutex`]: crate::sync::Mutex
95 /// [`RwLock`]: crate::sync::RwLock
96 #[stable(feature = "rust1", since = "1.0.0")]
97 pub enum TryLockError<T> {
98     /// The lock could not be acquired because another thread failed while holding
99     /// the lock.
100     #[stable(feature = "rust1", since = "1.0.0")]
101     Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
102     /// The lock could not be acquired at this time because the operation would
103     /// otherwise block.
104     #[stable(feature = "rust1", since = "1.0.0")]
105     WouldBlock,
106 }
107
108 /// A type alias for the result of a lock method which can be poisoned.
109 ///
110 /// The [`Ok`] variant of this result indicates that the primitive was not
111 /// poisoned, and the `Guard` is contained within. The [`Err`] variant indicates
112 /// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
113 /// the associated guard, and it can be acquired through the [`into_inner`]
114 /// method.
115 ///
116 /// [`into_inner`]: PoisonError::into_inner
117 #[stable(feature = "rust1", since = "1.0.0")]
118 pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;
119
120 /// A type alias for the result of a nonblocking locking method.
121 ///
122 /// For more information, see [`LockResult`]. A `TryLockResult` doesn't
123 /// necessarily hold the associated guard in the [`Err`] type as the lock may not
124 /// have been acquired for other reasons.
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
127
128 #[stable(feature = "rust1", since = "1.0.0")]
129 impl<T> fmt::Debug for PoisonError<T> {
130     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131         f.debug_struct("PoisonError").finish_non_exhaustive()
132     }
133 }
134
135 #[stable(feature = "rust1", since = "1.0.0")]
136 impl<T> fmt::Display for PoisonError<T> {
137     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138         "poisoned lock: another task failed inside".fmt(f)
139     }
140 }
141
142 #[stable(feature = "rust1", since = "1.0.0")]
143 impl<T> Error for PoisonError<T> {
144     #[allow(deprecated)]
145     fn description(&self) -> &str {
146         "poisoned lock: another task failed inside"
147     }
148 }
149
150 impl<T> PoisonError<T> {
151     /// Creates a `PoisonError`.
152     ///
153     /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
154     /// or [`RwLock::read`](crate::sync::RwLock::read).
155     #[stable(feature = "sync_poison", since = "1.2.0")]
156     pub fn new(guard: T) -> PoisonError<T> {
157         PoisonError { guard }
158     }
159
160     /// Consumes this error indicating that a lock is poisoned, returning the
161     /// underlying guard to allow access regardless.
162     ///
163     /// # Examples
164     ///
165     /// ```
166     /// use std::collections::HashSet;
167     /// use std::sync::{Arc, Mutex};
168     /// use std::thread;
169     ///
170     /// let mutex = Arc::new(Mutex::new(HashSet::new()));
171     ///
172     /// // poison the mutex
173     /// let c_mutex = Arc::clone(&mutex);
174     /// let _ = thread::spawn(move || {
175     ///     let mut data = c_mutex.lock().unwrap();
176     ///     data.insert(10);
177     ///     panic!();
178     /// }).join();
179     ///
180     /// let p_err = mutex.lock().unwrap_err();
181     /// let data = p_err.into_inner();
182     /// println!("recovered {} items", data.len());
183     /// ```
184     #[stable(feature = "sync_poison", since = "1.2.0")]
185     pub fn into_inner(self) -> T {
186         self.guard
187     }
188
189     /// Reaches into this error indicating that a lock is poisoned, returning a
190     /// reference to the underlying guard to allow access regardless.
191     #[stable(feature = "sync_poison", since = "1.2.0")]
192     pub fn get_ref(&self) -> &T {
193         &self.guard
194     }
195
196     /// Reaches into this error indicating that a lock is poisoned, returning a
197     /// mutable reference to the underlying guard to allow access regardless.
198     #[stable(feature = "sync_poison", since = "1.2.0")]
199     pub fn get_mut(&mut self) -> &mut T {
200         &mut self.guard
201     }
202 }
203
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T> From<PoisonError<T>> for TryLockError<T> {
206     fn from(err: PoisonError<T>) -> TryLockError<T> {
207         TryLockError::Poisoned(err)
208     }
209 }
210
211 #[stable(feature = "rust1", since = "1.0.0")]
212 impl<T> fmt::Debug for TryLockError<T> {
213     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214         match *self {
215             TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
216             TryLockError::WouldBlock => "WouldBlock".fmt(f),
217         }
218     }
219 }
220
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T> fmt::Display for TryLockError<T> {
223     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224         match *self {
225             TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
226             TryLockError::WouldBlock => "try_lock failed because the operation would block",
227         }
228         .fmt(f)
229     }
230 }
231
232 #[stable(feature = "rust1", since = "1.0.0")]
233 impl<T> Error for TryLockError<T> {
234     #[allow(deprecated, deprecated_in_future)]
235     fn description(&self) -> &str {
236         match *self {
237             TryLockError::Poisoned(ref p) => p.description(),
238             TryLockError::WouldBlock => "try_lock failed because the operation would block",
239         }
240     }
241
242     #[allow(deprecated)]
243     fn cause(&self) -> Option<&dyn Error> {
244         match *self {
245             TryLockError::Poisoned(ref p) => Some(p),
246             _ => None,
247         }
248     }
249 }
250
251 pub fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
252 where
253     F: FnOnce(T) -> U,
254 {
255     match result {
256         Ok(t) => Ok(f(t)),
257         Err(PoisonError { guard }) => Err(PoisonError::new(f(guard))),
258     }
259 }