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` and `std::lazy`. 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 `SyncLazy` 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
70#[cfg(any(test, feature = "std"))]
71extern crate core;
72
73#[cfg(feature = "portable-atomic")]
74extern crate portable_atomic;
75
76#[cfg(not(feature = "portable-atomic"))]
77use core::sync::atomic;
78#[cfg(feature = "portable-atomic")]
79use portable_atomic as atomic;
80
81#[cfg(feature = "barrier")]
82#[cfg_attr(docsrs, doc(cfg(feature = "barrier")))]
83pub mod barrier;
84#[cfg(feature = "lazy")]
85#[cfg_attr(docsrs, doc(cfg(feature = "lazy")))]
86pub mod lazy;
87#[cfg(feature = "mutex")]
88#[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
89pub mod mutex;
90#[cfg(feature = "once")]
91#[cfg_attr(docsrs, doc(cfg(feature = "once")))]
92pub mod once;
93pub mod relax;
94#[cfg(feature = "rwlock")]
95#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
96pub mod rwlock;
97
98#[cfg(feature = "mutex")]
99#[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
100pub use mutex::MutexGuard;
101#[cfg(feature = "std")]
102#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
103pub use relax::Yield;
104pub use relax::{RelaxStrategy, Spin};
105#[cfg(feature = "rwlock")]
106#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
107pub use rwlock::RwLockReadGuard;
108
109// Avoid confusing inference errors by aliasing away the relax strategy parameter. Users that need to use a different
110// relax strategy can do so by accessing the types through their fully-qualified path. This is a little bit horrible
111// but sadly adding a default type parameter is *still* a breaking change in Rust (for understandable reasons).
112
113/// A primitive that synchronizes the execution of multiple threads. See [`barrier::Barrier`] for documentation.
114///
115/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
116/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
117#[cfg(feature = "barrier")]
118#[cfg_attr(docsrs, doc(cfg(feature = "barrier")))]
119pub type Barrier = crate::barrier::Barrier;
120
121/// A value which is initialized on the first access. See [`lazy::Lazy`] for documentation.
122///
123/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
124/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
125#[cfg(feature = "lazy")]
126#[cfg_attr(docsrs, doc(cfg(feature = "lazy")))]
127pub type Lazy<T, F = fn() -> T> = crate::lazy::Lazy<T, F>;
128
129/// A primitive that synchronizes the execution of multiple threads. See [`mutex::Mutex`] for documentation.
130///
131/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
132/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
133#[cfg(feature = "mutex")]
134#[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
135pub type Mutex<T> = crate::mutex::Mutex<T>;
136
137/// A primitive that provides lazy one-time initialization. See [`once::Once`] for documentation.
138///
139/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
140/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
141#[cfg(feature = "once")]
142#[cfg_attr(docsrs, doc(cfg(feature = "once")))]
143pub type Once<T = ()> = crate::once::Once<T>;
144
145/// A lock that provides data access to either one writer or many readers. See [`rwlock::RwLock`] for documentation.
146///
147/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
148/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
149#[cfg(feature = "rwlock")]
150#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
151pub type RwLock<T> = crate::rwlock::RwLock<T>;
152
153/// A guard that provides immutable data access but can be upgraded to [`RwLockWriteGuard`]. See
154/// [`rwlock::RwLockUpgradableGuard`] for documentation.
155///
156/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
157/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
158#[cfg(feature = "rwlock")]
159#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
160pub type RwLockUpgradableGuard<'a, T> = crate::rwlock::RwLockUpgradableGuard<'a, T>;
161
162/// A guard that provides mutable data access. See [`rwlock::RwLockWriteGuard`] for documentation.
163///
164/// A note for advanced users: this alias exists to avoid subtle type inference errors due to the default relax
165/// strategy type parameter. If you need a non-default relax strategy, use the fully-qualified path.
166#[cfg(feature = "rwlock")]
167#[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
168pub type RwLockWriteGuard<'a, T> = crate::rwlock::RwLockWriteGuard<'a, T>;
169
170/// Spin synchronisation primitives, but compatible with [`lock_api`](https://crates.io/crates/lock_api).
171#[cfg(feature = "lock_api")]
172#[cfg_attr(docsrs, doc(cfg(feature = "lock_api")))]
173pub mod lock_api {
174 /// A lock that provides mutually exclusive data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
175 #[cfg(feature = "mutex")]
176 #[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
177 pub type Mutex<T> = lock_api_crate::Mutex<crate::Mutex<()>, T>;
178
179 /// A guard that provides mutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
180 #[cfg(feature = "mutex")]
181 #[cfg_attr(docsrs, doc(cfg(feature = "mutex")))]
182 pub type MutexGuard<'a, T> = lock_api_crate::MutexGuard<'a, crate::Mutex<()>, T>;
183
184 /// A lock that provides data access to either one writer or many readers (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
185 #[cfg(feature = "rwlock")]
186 #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
187 pub type RwLock<T> = lock_api_crate::RwLock<crate::RwLock<()>, T>;
188
189 /// A guard that provides immutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
190 #[cfg(feature = "rwlock")]
191 #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
192 pub type RwLockReadGuard<'a, T> = lock_api_crate::RwLockReadGuard<'a, crate::RwLock<()>, T>;
193
194 /// A guard that provides mutable data access (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
195 #[cfg(feature = "rwlock")]
196 #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
197 pub type RwLockWriteGuard<'a, T> = lock_api_crate::RwLockWriteGuard<'a, crate::RwLock<()>, T>;
198
199 /// A guard that provides immutable data access but can be upgraded to [`RwLockWriteGuard`] (compatible with [`lock_api`](https://crates.io/crates/lock_api)).
200 #[cfg(feature = "rwlock")]
201 #[cfg_attr(docsrs, doc(cfg(feature = "rwlock")))]
202 pub type RwLockUpgradableReadGuard<'a, T> =
203 lock_api_crate::RwLockUpgradableReadGuard<'a, crate::RwLock<()>, T>;
204}
205
206/// In the event of an invalid operation, it's best to abort the current process.
207#[cfg(feature = "fair_mutex")]
208fn abort() -> ! {
209 #[cfg(not(feature = "std"))]
210 {
211 // Panicking while panicking is defined by Rust to result in an abort.
212 struct Panic;
213
214 impl Drop for Panic {
215 fn drop(&mut self) {
216 panic!("aborting due to invalid operation");
217 }
218 }
219
220 let _panic = Panic;
221 panic!("aborting due to invalid operation");
222 }
223
224 #[cfg(feature = "std")]
225 {
226 std::process::abort();
227 }
228}