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