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;
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
268impl<T> PoisonError<T> {
269 /// Creates a `PoisonError`.
270 ///
271 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
272 /// or [`RwLock::read`](crate::sync::RwLock::read).
273 ///
274 /// This method may panic if std was built with `panic="abort"`.
275 #[cfg(panic = "unwind")]
276 #[stable(feature = "sync_poison", since = "1.2.0")]
277 pub fn new(data: T) -> PoisonError<T> {
278 PoisonError { data }
279 }
280
281 /// Creates a `PoisonError`.
282 ///
283 /// This is generally created by methods like [`Mutex::lock`](crate::sync::Mutex::lock)
284 /// or [`RwLock::read`](crate::sync::RwLock::read).
285 ///
286 /// This method may panic if std was built with `panic="abort"`.
287 #[cfg(not(panic = "unwind"))]
288 #[stable(feature = "sync_poison", since = "1.2.0")]
289 #[track_caller]
290 pub fn new(_data: T) -> PoisonError<T> {
291 panic!("PoisonError created in a libstd built with panic=\"abort\"")
292 }
293
294 /// Consumes this error indicating that a lock is poisoned, returning the
295 /// associated data.
296 ///
297 /// # Examples
298 ///
299 /// ```
300 /// use std::collections::HashSet;
301 /// use std::sync::{Arc, Mutex};
302 /// use std::thread;
303 ///
304 /// let mutex = Arc::new(Mutex::new(HashSet::new()));
305 ///
306 /// // poison the mutex
307 /// let c_mutex = Arc::clone(&mutex);
308 /// let _ = thread::spawn(move || {
309 /// let mut data = c_mutex.lock().unwrap();
310 /// data.insert(10);
311 /// panic!();
312 /// }).join();
313 ///
314 /// let p_err = mutex.lock().unwrap_err();
315 /// let data = p_err.into_inner();
316 /// println!("recovered {} items", data.len());
317 /// ```
318 #[stable(feature = "sync_poison", since = "1.2.0")]
319 pub fn into_inner(self) -> T {
320 self.data
321 }
322
323 /// Reaches into this error indicating that a lock is poisoned, returning a
324 /// reference to the associated data.
325 #[stable(feature = "sync_poison", since = "1.2.0")]
326 pub fn get_ref(&self) -> &T {
327 &self.data
328 }
329
330 /// Reaches into this error indicating that a lock is poisoned, returning a
331 /// mutable reference to the associated data.
332 #[stable(feature = "sync_poison", since = "1.2.0")]
333 pub fn get_mut(&mut self) -> &mut T {
334 &mut self.data
335 }
336}
337
338#[stable(feature = "rust1", since = "1.0.0")]
339impl<T> From<PoisonError<T>> for TryLockError<T> {
340 fn from(err: PoisonError<T>) -> TryLockError<T> {
341 TryLockError::Poisoned(err)
342 }
343}
344
345#[stable(feature = "rust1", since = "1.0.0")]
346impl<T> fmt::Debug for TryLockError<T> {
347 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
348 match *self {
349 #[cfg(panic = "unwind")]
350 TryLockError::Poisoned(..) => "Poisoned(..)".fmt(f),
351 #[cfg(not(panic = "unwind"))]
352 TryLockError::Poisoned(ref p) => match p._never {},
353 TryLockError::WouldBlock => "WouldBlock".fmt(f),
354 }
355 }
356}
357
358#[stable(feature = "rust1", since = "1.0.0")]
359impl<T> fmt::Display for TryLockError<T> {
360 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
361 match *self {
362 #[cfg(panic = "unwind")]
363 TryLockError::Poisoned(..) => "poisoned lock: another task failed inside",
364 #[cfg(not(panic = "unwind"))]
365 TryLockError::Poisoned(ref p) => match p._never {},
366 TryLockError::WouldBlock => "try_lock failed because the operation would block",
367 }
368 .fmt(f)
369 }
370}
371
372#[stable(feature = "rust1", since = "1.0.0")]
373impl<T> Error for TryLockError<T> {
374 #[allow(deprecated)]
375 fn cause(&self) -> Option<&dyn Error> {
376 match *self {
377 #[cfg(panic = "unwind")]
378 TryLockError::Poisoned(ref p) => Some(p),
379 #[cfg(not(panic = "unwind"))]
380 TryLockError::Poisoned(ref p) => match p._never {},
381 _ => None,
382 }
383 }
384}
385
386pub(crate) fn map_result<T, U, F>(result: LockResult<T>, f: F) -> LockResult<U>
387where
388 F: FnOnce(T) -> U,
389{
390 match result {
391 Ok(t) => Ok(f(t)),
392 #[cfg(panic = "unwind")]
393 Err(PoisonError { data }) => Err(PoisonError::new(f(data))),
394 }
395}