axiom_spinlock/
lib.rs

1//! # axiom-spinlock 🌀
2//!
3//! A lightweight, **`no_std`-compatible** crate providing a minimal and efficient
4//! **spin-based synchronization primitive** for low-level concurrent programming.
5//!
6//! The crate includes:
7//!
8//! - [`SpinLock<T>`] — a simple, fair spinlock for mutual exclusion.
9//! - [`BackOff`] — an adaptive exponential backoff for reducing contention.
10//!
11//! Designed for environments where blocking is **not an option**—such as kernels,
12//! embedded runtimes, or custom executors—this crate avoids OS-level locking
13//! and context switching entirely.
14//!
15//! ## ✨ Features
16//!
17//! - ✅ `no_std` compatible (uses `core` only)
18//! - ⚙️ Optional `std` feature to yield CPU (`std::thread::yield_now()`)
19//! - 🧩 Adaptive backoff strategy for high-contention locks
20//! - 🔒 Atomic test-and-set spinlock with RAII guard
21//!
22//! ## 🚀 Quick Example
23//!
24//! ```rust
25//! use axiom_spinlock::{SpinLock, BackOff};
26//!
27//! // Example 1: Using SpinLock
28//! let lock = SpinLock::new(0);
29//! {
30//!     let mut guard = lock.lock();
31//!     *guard += 1;
32//! } // automatically unlocked when guard is dropped
33//! assert_eq!(*lock.lock(), 1);
34//!
35//! // Example 2: Using BackOff manually
36//! let backoff = BackOff::new();
37//! for _ in 0..5 {
38//!     backoff.wait();
39//! }
40//! ```
41//!
42//! ## 🧠 Design
43//!
44//! ### SpinLock
45//!
46//! `SpinLock` uses an [`AtomicBool`] to implement a test-and-set mechanism,
47//! ensuring mutual exclusion. It guarantees proper memory ordering using
48//! **Acquire/Release** semantics and automatically releases the lock when the
49//! [`SpinGuard`] is dropped.
50//!
51//! ### BackOff
52//!
53//! `BackOff` performs an adaptive exponential backoff, using
54//! [`core::hint::spin_loop()`] to signal the processor that it’s in a busy-wait
55//! loop. When compiled with `std`, the backoff escalates to a cooperative
56//! `std::thread::yield_now()` after prolonged contention.
57//!
58//! ## ⚠️ Safety & Usage Notes
59//!
60//! - Prefer `SpinLock` for **short critical sections** only.  
61//! - Never hold a spinlock during blocking or long-running operations.  
62//! - `BackOff` is meant to complement spinning mechanisms for fairness and CPU efficiency.  
63//! - `SpinLock` is **not reentrant**.
64//!
65//! ## 📦 Modules
66//!
67//! - [`backoff`] — Adaptive exponential backoff mechanism.  
68//! - [`spinlock`] — Spin-based synchronization primitive.  
69//!
70//!
71//! ### Crate Exports
72//!
73//! - [`BackOff`] — from [`backoff`]  
74//! - [`SpinLock`] — from [`spinlock`]
75
76pub mod backoff;
77pub mod spinlock;
78
79pub use backoff::BackOff;
80pub use spinlock::SpinLock;