Skip to main content

spin/
lib.rs

1#![cfg_attr(all(not(feature = "std"), not(test)), no_std)]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![deny(missing_docs)]
4
5//! This crate provides [spin-based](https://en.wikipedia.org/wiki/Spinlock) versions of the
6//! primitives in `std::sync`. Because synchronization is done through spinning,
7//! the primitives are suitable for use in `no_std` environments.
8//!
9//! # Features
10//!
11//! - `Mutex`, `RwLock`, `Once`/`SyncOnceCell`, and `LazyLock` equivalents
12//!
13//! - Support for `no_std` environments
14//!
15//! - [`lock_api`](https://crates.io/crates/lock_api) compatibility
16//!
17//! - Upgradeable `RwLock` guards
18//!
19//! - Guards can be sent and shared between threads
20//!
21//! - Guard leaking
22//!
23//! - Ticket locks
24//!
25//! - Different strategies for dealing with contention
26//!
27//! # Relationship with `std::sync`
28//!
29//! While `spin` is not a drop-in replacement for `std::sync` (and
30//! [should not be considered as such](https://matklad.github.io/2020/01/02/spinlocks-considered-harmful.html))
31//! an effort is made to keep this crate reasonably consistent with `std::sync`.
32//!
33//! Many of the types defined in this crate have 'additional capabilities' when compared to `std::sync`:
34//!
35//! - Because spinning does not depend on the thread-driven model of `std::sync`, guards ([`MutexGuard`],
36//!   [`RwLockReadGuard`], [`RwLockWriteGuard`], etc.) may be sent and shared between threads.
37//!
38//! - [`RwLockUpgradableGuard`] supports being upgraded into a [`RwLockWriteGuard`].
39//!
40//! - Guards support [leaking](https://doc.rust-lang.org/nomicon/leaking.html).
41//!
42//! - [`Once`] owns the value returned by its `call_once` initializer.
43//!
44//! - [`RwLock`] supports counting readers and writers.
45//!
46//! Conversely, the types in this crate do not have some of the features `std::sync` has:
47//!
48//! - Locks do not track [panic poisoning](https://doc.rust-lang.org/nomicon/poisoning.html).
49//!
50//! ## Feature flags
51//!
52//! The crate comes with a few feature flags that you may wish to use.
53//!
54//! - `lock_api` enables support for [`lock_api`](https://crates.io/crates/lock_api)
55//!
56//! - `ticket_mutex` uses a ticket lock for the implementation of `Mutex`
57//!
58//! - `fair_mutex` enables a fairer implementation of `Mutex` that uses eventual fairness to avoid
59//!   starvation
60//!
61//! - `std` enables support for thread yielding instead of spinning
62//!
63//! - `portable-atomic` enables usage of the `portable-atomic` crate
64//!   to support platforms without native atomic operations (Cortex-M0, etc.).
65//!   See the documentation for the `portable-atomic` crate for more information
66//!   with some requirements for no-std build:
67//!   <https://github.com/taiki-e/portable-atomic#optional-features>
68
69#[cfg(any(test, feature = "std"))]
70extern crate core;
71
72#[cfg(feature = "portable-atomic")]
73extern crate portable_atomic;
74
75#[cfg(not(feature = "portable-atomic"))]
76use core::sync::atomic;
77#[cfg(feature = "portable-atomic")]
78use portable_atomic as atomic;
79
80#[cfg(feature = "barrier")]
81#[cfg_attr(docsrs, doc(cfg(feature = "barrier")))]
82pub mod barrier;
83#[cfg(feature = "lazylock")]
84#[cfg_attr(docsrs, doc(cfg(feature = "lazylock")))]
85pub mod lazylock;
86#[cfg(feature = "mutex")]
87#[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
88pub mod mutex;
89#[cfg(feature = "once")]
90#[cfg_attr(docsrs, doc(cfg(feature = "once")))]
91pub mod once;
92pub mod relax;
93#[cfg(feature = "rwlock")]
94#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
95pub mod rwlock;
96
97#[cfg(feature = "mutex")]
98#[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
99pub use mutex::MutexGuard;
100#[cfg(feature = "std")]
101#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
102pub use relax::Yield;
103pub use relax::{RelaxStrategy, Spin};
104#[cfg(feature = "rwlock")]
105#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
106pub use rwlock::RwLockReadGuard;
107
108// Avoid confusing inference errors by aliasing away the relax strategy parameter. Users that need to use a different
109// relax strategy can do so by accessing the types through their fully-qualified path. This is a little bit horrible
110// but sadly adding a default type parameter is *still* a breaking change in Rust (for understandable reasons).
111
112/// A primitive that synchronizes the execution of multiple threads. See [`barrier::Barrier`] for documentation.
113///
114/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
115/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
116#[cfg(feature = "barrier")]
117#[cfg_attr(docsrs, doc(cfg(feature = "barrier")))]
118pub type Barrier = crate::barrier::Barrier;
119
120/// A value which is initialized on the first access. See [`lazylock::LazyLock`] for documentation.
121///
122/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
123/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
124#[cfg(feature = "lazylock")]
125#[cfg_attr(docsrs, doc(cfg(feature = "lazylock")))]
126pub type LazyLock<T, F = fn() -> T> = crate::lazylock::LazyLock<T, F>;
127
128/// A type alias to [`LazyLock`] for compatibility reasons.
129///
130#[deprecated(note = "use `spin::LazyLock` instead")]
131#[cfg(feature = "lazylock")]
132#[cfg_attr(docsrs, doc(cfg(feature = "lazylock")))]
133pub type Lazy<T, F = fn() -> T> = crate::lazylock::LazyLock<T, F>;
134
135/// A primitive that synchronizes the execution of multiple threads. See [`mutex::Mutex`] for documentation.
136///
137/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
138/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
139#[cfg(feature = "mutex")]
140#[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
141pub type Mutex<T> = crate::mutex::Mutex<T>;
142
143/// A primitive that provides lazy one-time initialization. See [`once::Once`] for documentation.
144///
145/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
146/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
147#[cfg(feature = "once")]
148#[cfg_attr(docsrs, doc(cfg(feature = "once")))]
149pub type Once<T = ()> = crate::once::Once<T>;
150
151/// A lock that provides data access to either one writer or many readers. See [`rwlock::RwLock`] for documentation.
152///
153/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
154/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
155#[cfg(feature = "rwlock")]
156#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
157pub type RwLock<T> = crate::rwlock::RwLock<T>;
158
159/// A guard that provides immutable data access but can be upgraded to [`RwLockWriteGuard`]. See
160/// [`rwlock::RwLockUpgradableGuard`] for documentation.
161///
162/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
163/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
164#[cfg(feature = "rwlock")]
165#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
166pub type RwLockUpgradableGuard<'a, T> = crate::rwlock::RwLockUpgradableGuard<'a, T>;
167
168/// A guard that provides mutable data access. See [`rwlock::RwLockWriteGuard`] for documentation.
169///
170/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
171/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
172#[cfg(feature = "rwlock")]
173#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
174pub type RwLockWriteGuard<'a, T> = crate::rwlock::RwLockWriteGuard<'a, T>;
175
176/// Spin synchronisation primitives, but compatible with [`lock_api`](https://crates.io/crates/lock_api).
177#[cfg(feature = "lock_api")]
178#[cfg_attr(docsrs, doc(cfg(feature = "lock_api")))]
179pub mod lock_api {
180    /// A lock that provides mutually exclusive data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
181    #[cfg(feature = "mutex")]
182    #[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
183    pub type Mutex<T> = lock_api_crate::Mutex<crate::Mutex<()>, T>;
184
185    /// A guard that provides mutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
186    #[cfg(feature = "mutex")]
187    #[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
188    pub type MutexGuard<'a, T> = lock_api_crate::MutexGuard<'a, crate::Mutex<()>, T>;
189
190    /// A lock that provides data access to either one writer or many readers (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
191    #[cfg(feature = "rwlock")]
192    #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
193    pub type RwLock<T> = lock_api_crate::RwLock<crate::RwLock<()>, T>;
194
195    /// A guard that provides immutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
196    #[cfg(feature = "rwlock")]
197    #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
198    pub type RwLockReadGuard<'a, T> = lock_api_crate::RwLockReadGuard<'a, crate::RwLock<()>, T>;
199
200    /// A guard that provides mutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
201    #[cfg(feature = "rwlock")]
202    #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
203    pub type RwLockWriteGuard<'a, T> = lock_api_crate::RwLockWriteGuard<'a, crate::RwLock<()>, T>;
204
205    /// A guard that provides immutable data access but can be upgraded to [`RwLockWriteGuard`] (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
206    #[cfg(feature = "rwlock")]
207    #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
208    pub type RwLockUpgradableReadGuard<'a, T> =
209        lock_api_crate::RwLockUpgradableReadGuard<'a, crate::RwLock<()>, T>;
210
211    /// A guard returned by [RwLockReadGuard::map] that provides immutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
212    #[cfg(feature = "rwlock")]
213    #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
214    pub type MappedRwLockReadGuard<'a, T> =
215        lock_api_crate::MappedRwLockReadGuard<'a, crate::RwLock<()>, T>;
216
217    /// A guard returned by [RwLockWriteGuard::map] that provides mutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
218    #[cfg(feature = "rwlock")]
219    #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
220    pub type MappedRwLockWriteGuard<'a, T> =
221        lock_api_crate::MappedRwLockWriteGuard<'a, crate::RwLock<()>, T>;
222}
223
224/// In the event of an invalid operation, it's best to abort the current process.
225#[cfg(feature = "fair_mutex")]
226fn abort() -> ! {
227    #[cfg(not(feature = "std"))]
228    {
229        // Panicking while panicking is defined by Rust to result in an abort.
230        struct Panic;
231
232        impl Drop for Panic {
233            fn drop(&mut self) {
234                panic!("aborting due to invalid operation");
235            }
236        }
237
238        let _panic = Panic;
239        panic!("aborting due to invalid operation");
240    }
241
242    #[cfg(feature = "std")]
243    {
244        std::process::abort();
245    }
246}