std/sync/poison.rs
1//! Synchronization objects that employ poisoning.
2//!
3//! # Poisoning
4//!
5//! All synchronization objects in this module implement a strategy called
6//! "poisoning" where a primitive becomes poisoned if it recognizes that some
7//! thread has panicked while holding the exclusive access granted by the
8//! primitive. This information is then propagated to all other threads
9//! to signify that the data protected by this primitive is likely tainted
10//! (some invariant is not being upheld).
11//!
12//! The specifics of how this "poisoned" state affects other threads and whether
13//! the panics are recognized reliably or on a best-effort basis depend on the
14//! primitive. See [Overview](#overview) below.
15//!
16//! The synchronization objects in this module have alternative implementations that do not employ
17//! poisoning in the [`std::sync::nonpoison`] module.
18//!
19//! [`std::sync::nonpoison`]: crate::sync::nonpoison
20//!
21//! # Overview
22//!
23//! Below is a list of synchronization objects provided by this module
24//! with a high-level overview for each object and a description
25//! of how it employs "poisoning".
26//!
27//! - [`Condvar`]: Condition Variable, providing the ability to block
28//! a thread while waiting for an event to occur.
29//!
30//! Condition variables are typically associated with
31//! a boolean predicate (a condition) and a mutex.
32//! This implementation is associated with [`poison::Mutex`](Mutex),
33//! which employs poisoning.
34//! For this reason, [`Condvar::wait()`] will return a [`LockResult`],
35//! just like [`poison::Mutex::lock()`](Mutex::lock) does.
36//!
37//! - [`Mutex`]: Mutual Exclusion mechanism, which ensures that at
38//! most one thread at a time is able to access some data.
39//!
40//! Panicking while holding the lock typically poisons the mutex, but it is
41//! not guaranteed to detect this condition in all circumstances.
42//! [`Mutex::lock()`] returns a [`LockResult`], providing a way to deal with
43//! the poisoned state. See [`Mutex`'s documentation](Mutex#poisoning) for more.
44//!
45//! - [`RwLock`]: Provides a mutual exclusion mechanism which allows
46//! multiple readers at the same time, while allowing only one
47//! writer at a time. In some cases, this can be more efficient than
48//! a mutex.
49//!
50//! This implementation, like [`Mutex`], usually becomes poisoned on a panic.
51//! Note, however, that an `RwLock` may only be poisoned if a panic occurs
52//! while it is locked exclusively (write mode). If a panic occurs in any reader,
53//! then the lock will not be poisoned.
54//!
55//! Note that the [`Once`] type also employs poisoning, but since it has non-poisoning `force`
56//! methods available on it, there is no separate `nonpoison` and `poison` version.
57//!
58//! [`Once`]: crate::sync::Once
59
60#[stable(feature = "rust1", since = "1.0.0")]
61pub use self::condvar::Condvar;
62#[unstable(feature = "mapped_lock_guards", issue = "117108")]
63pub use self::mutex::MappedMutexGuard;
64#[stable(feature = "rust1", since = "1.0.0")]
65pub use self::mutex::{Mutex, MutexGuard};
66#[unstable(feature = "mapped_lock_guards", issue = "117108")]
67pub use self::rwlock::{MappedRwLockReadGuard, MappedRwLockWriteGuard};
68#[stable(feature = "rust1", since = "1.0.0")]
69pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
70use crate::error::Error;
71use crate::fmt;
72#[cfg(panic = "unwind")]
73use crate::sync::atomic::{Atomic, AtomicBool, Ordering};
74#[cfg(panic = "unwind")]
75use crate::thread;
76
77mod condvar;
78#[stable(feature = "rust1", since = "1.0.0")]
79mod mutex;
80mod rwlock;
81
82pub(crate) struct Flag {
83 #[cfg(panic = "unwind")]
84 failed: Atomic<bool>,
85}
86
87// Note that the Ordering uses to access the `failed` field of `Flag` below is
88// always `Relaxed`, and that's because this isn't actually protecting any data,
89// it's just a flag whether we've panicked or not.
90//
91// The actual location that this matters is when a mutex is **locked** which is
92// where we have external synchronization ensuring that we see memory
93// reads/writes to this flag.
94//
95// As a result, if it matters, we should see the correct value for `failed` in
96// all cases.
97
98impl Flag {
99 #[inline]
100 pub const fn new() -> Flag {
101 Flag {
102 #[cfg(panic = "unwind")]
103 failed: AtomicBool::new(false),
104 }
105 }
106
107 /// Checks the flag for an unguarded borrow, where we only care about existing poison.
108 #[inline]
109 pub fn borrow(&self) -> LockResult<()> {
110 if self.get() { Err(PoisonError::new(())) } else { Ok(()) }
111 }
112
113 /// Checks the flag for a guarded borrow, where we may also set poison when `done`.
114 #[inline]
115 pub fn guard(&self) -> LockResult<Guard> {
116 let ret = Guard {
117 #[cfg(panic = "unwind")]
118 panicking: thread::panicking(),
119 };
120 if self.get() { Err(PoisonError::new(ret)) } else { Ok(ret) }
121 }
122
123 #[inline]
124 #[cfg(panic = "unwind")]
125 pub fn done(&self, guard: &Guard) {
126 if !guard.panicking && thread::panicking() {
127 self.failed.store(true, Ordering::Relaxed);
128 }
129 }
130
131 #[inline]
132 #[cfg(not(panic = "unwind"))]
133 pub fn done(&self, _guard: &Guard) {}
134
135 #[inline]
136 #[cfg(panic = "unwind")]
137 pub fn get(&self) -> bool {
138 self.failed.load(Ordering::Relaxed)
139 }
140
141 #[inline(always)]
142 #[cfg(not(panic = "unwind"))]
143 pub fn get(&self) -> bool {
144 false
145 }
146
147 #[inline]
148 pub fn clear(&self) {
149 #[cfg(panic = "unwind")]
150 self.failed.store(false, Ordering::Relaxed)
151 }
152}
153
154#[derive(Clone)]
155pub(crate) struct Guard {
156 #[cfg(panic = "unwind")]
157 panicking: bool,
158}
159
160/// A type of error which can be returned whenever a lock is acquired.
161///
162/// Both [`Mutex`]es and [`RwLock`]s are poisoned whenever a thread fails while the lock
163/// is held. The precise semantics for when a lock is poisoned is documented on
164/// each lock. For a lock in the poisoned state, unless the state is cleared manually,
165/// all future acquisitions will return this error.
166///
167/// # Examples
168///
169/// ```
170/// use std::sync::{Arc, Mutex};
171/// use std::thread;
172///
173/// let mutex = Arc::new(Mutex::new(1));
174///
175/// // poison the mutex
176/// let c_mutex = Arc::clone(&mutex);
177/// let _ = thread::spawn(move || {
178/// let mut data = c_mutex.lock().unwrap();
179/// *data = 2;
180/// panic!();
181/// }).join();
182///
183/// match mutex.lock() {
184/// Ok(_) => unreachable!(),
185/// Err(p_err) => {
186/// let data = p_err.get_ref();
187/// println!("recovered: {data}");
188/// }
189/// };
190/// ```
191/// [`Mutex`]: crate::sync::Mutex
192/// [`RwLock`]: crate::sync::RwLock
193#[stable(feature = "rust1", since = "1.0.0")]
194pub struct PoisonError<T> {
195 data: T,
196 #[cfg(not(panic = "unwind"))]
197 _never: !,
198}
199
200/// An enumeration of possible errors associated with a [`TryLockResult`] which
201/// can occur while trying to acquire a lock, from the [`try_lock`] method on a
202/// [`Mutex`] or the [`try_read`] and [`try_write`] methods on an [`RwLock`].
203///
204/// [`try_lock`]: crate::sync::Mutex::try_lock
205/// [`try_read`]: crate::sync::RwLock::try_read
206/// [`try_write`]: crate::sync::RwLock::try_write
207/// [`Mutex`]: crate::sync::Mutex
208/// [`RwLock`]: crate::sync::RwLock
209#[stable(feature = "rust1", since = "1.0.0")]
210pub enum TryLockError<T> {
211 /// The lock could not be acquired because another thread failed while holding
212 /// the lock.
213 #[stable(feature = "rust1", since = "1.0.0")]
214 Poisoned(#[stable(feature = "rust1", since = "1.0.0")] PoisonError<T>),
215 /// The lock could not be acquired at this time because the operation would
216 /// otherwise block.
217 #[stable(feature = "rust1", since = "1.0.0")]
218 WouldBlock,
219}
220
221/// A type alias for the result of a lock method which can be poisoned.
222///
223/// The [`Ok`] variant of this result indicates that the primitive was not
224/// poisoned, and the operation result is contained within. The [`Err`] variant indicates
225/// that the primitive was poisoned. Note that the [`Err`] variant *also* carries
226/// an associated value assigned by the lock method, and it can be acquired through the
227/// [`into_inner`] method. The semantics of the associated value depends on the corresponding
228/// lock method.
229///
230/// [`into_inner`]: PoisonError::into_inner
231#[stable(feature = "rust1", since = "1.0.0")]
232pub type LockResult<T> = Result<T, PoisonError<T>>;
233
234/// A type alias for the result of a nonblocking locking method.
235///
236/// For more information, see [`LockResult`]. A `TryLockResult` doesn't
237/// necessarily hold the associated guard in the [`Err`] type as the lock might not
238/// have been acquired for other reasons.
239#[stable(feature = "rust1", since = "1.0.0")]
240pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;
241
242#[stable(feature = "rust1", since = "1.0.0")]
243impl<T> fmt::Debug for PoisonError<T> {
244 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245 f.debug_struct("PoisonError").finish_non_exhaustive()
246 }
247}
248
249#[stable(feature = "rust1", since = "1.0.0")]
250impl<T> fmt::Display for PoisonError<T> {
251 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
252 "poisoned lock: another task failed inside".fmt(f)
253 }
254}
255
256#[stable(feature = "rust1", since = "1.0.0")]
257impl<T> Error for PoisonError<T> {}
258
259impl<T> PoisonError<T> {
260 /// Creates a `PoisonError`.
261 ///
262 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
263 /// or [`RwLock::read`](crate::sync::RwLock::read).
264 ///
265 /// This method may panic if std was built with `panic="abort"`.
266 #[cfg(panic = "unwind")]
267 #[stable(feature = "sync_poison", since = "1.2.0")]
268 pub fn new(data: T) -> PoisonError<T> {
269 PoisonError { data }
270 }
271
272 /// Creates a `PoisonError`.
273 ///
274 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
275 /// or [`RwLock::read`](crate::sync::RwLock::read).
276 ///
277 /// This method may panic if std was built with `panic="abort"`.
278 #[cfg(not(panic = "unwind"))]
279 #[stable(feature = "sync_poison", since = "1.2.0")]
280 #[track_caller]
281 pub fn new(_data: T) -> PoisonError<T> {
282 panic!("PoisonError created in a libstd built with panic=\"abort\"")
283 }
284
285 /// Consumes this error indicating that a lock is poisoned, returning the
286 /// associated data.
287 ///
288 /// # Examples
289 ///
290 /// ```
291 /// use std::collections::HashSet;
292 /// use std::sync::{Arc, Mutex};
293 /// use std::thread;
294 ///
295 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
296 ///
297 /// // poison the mutex
298 /// let c_mutex = Arc::clone(&mutex);
299 /// let _ = thread::spawn(move || {
300 /// let mut data = c_mutex.lock().unwrap();
301 /// data.insert(10);
302 /// panic!();
303 /// }).join();
304 ///
305 /// let p_err = mutex.lock().unwrap_err();
306 /// let data = p_err.into_inner();
307 /// println!("recovered {} items", data.len());
308 /// ```
309 #[stable(feature = "sync_poison", since = "1.2.0")]
310 pub fn into_inner(self) -> T {
311 self.data
312 }
313
314 /// Reaches into this error indicating that a lock is poisoned, returning a
315 /// reference to the associated data.
316 #[stable(feature = "sync_poison", since = "1.2.0")]
317 pub fn get_ref(&self) -> &T {
318 &self.data
319 }
320
321 /// Reaches into this error indicating that a lock is poisoned, returning a
322 /// mutable reference to the associated data.
323 #[stable(feature = "sync_poison", since = "1.2.0")]
324 pub fn get_mut(&mut self) -> &mut T {
325 &mut self.data
326 }
327}
328
329#[stable(feature = "rust1", since = "1.0.0")]
330impl<T> From<PoisonError<T>> for TryLockError<T> {
331 fn from(err: PoisonError<T>) -> TryLockError<T> {
332 TryLockError::Poisoned(err)
333 }
334}
335
336#[stable(feature = "rust1", since = "1.0.0")]
337impl<T> fmt::Debug for TryLockError<T> {
338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
339 match *self {
340 #[cfg(panic = "unwind")]
341 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
342 #[cfg(not(panic = "unwind"))]
343 TryLockError::Poisoned(ref p) => match p._never {},
344 TryLockError::WouldBlock => "WouldBlock".fmt(f),
345 }
346 }
347}
348
349#[stable(feature = "rust1", since = "1.0.0")]
350impl<T> fmt::Display for TryLockError<T> {
351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
352 match *self {
353 #[cfg(panic = "unwind")]
354 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
355 #[cfg(not(panic = "unwind"))]
356 TryLockError::Poisoned(ref p) => match p._never {},
357 TryLockError::WouldBlock => "try_lock failed because the operation would block",
358 }
359 .fmt(f)
360 }
361}
362
363#[stable(feature = "rust1", since = "1.0.0")]
364impl<T> Error for TryLockError<T> {
365 #[allow(deprecated)]
366 fn cause(&self) -> Option<&dyn Error> {
367 match *self {
368 #[cfg(panic = "unwind")]
369 TryLockError::Poisoned(ref p) => Some(p),
370 #[cfg(not(panic = "unwind"))]
371 TryLockError::Poisoned(ref p) => match p._never {},
372 _ => None,
373 }
374 }
375}
376
377pub(crate) fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
378where
379 F: FnOnce(T) -> U,
380{
381 match result {
382 Ok(t) => Ok(f(t)),
383 #[cfg(panic = "unwind")]
384 Err(PoisonError { data }) => Err(PoisonError::new(f(data))),
385 }
386}