arc_swap/strategy/mod.rs
1//! Strategies for protecting the reference counts.
2//!
3//! There are multiple algorithms how to protect the reference counts while they're being updated
4//! by multiple threads, each with its own set of pros and cons. The [`DefaultStrategy`] is used by
5//! default and should generally be the least surprising option. It is possible to pick a different
6//! strategy.
7//!
8//! For now, the traits in here are sealed and don't expose any methods to the users of the crate.
9//! This is because we are not confident about the details just yet. In the future it may be
10//! possible for downstream users to implement their own, but for now it is only so users can
11//! choose one of the provided.
12//!
13//! It is expected that future strategies would come with different capabilities and limitations.
14//! In particular, some that are not "tight" in the cleanup (delay the cleanup) or not support the
15//! compare and swap operations.
16//!
17//! Currently, we have these strategies:
18//!
19//! * [`DefaultStrategy`] (this one is used implicitly)
20//! * [`RwLock<()>`][std::sync::RwLock]
21//!
22//! # The `RwLock<()>` strategy
23//!
24//! With the `rwlock-strategy` feature, [`RwLock<()>`][std::sync::RwLock] may be used as a strategy
25//! too. It doesn't have the performance characteristics or lock-free guarantees of the others, but
26//! it is much simpler and contains less `unsafe` code (actually, less code altogether): a load
27//! takes the read lock just long enough to increment the reference count, so a reader always holds
28//! an owned reference. Therefore, it can be used for testing purposes and cross-checking, or as a
29//! fallback by code that owns its [`ArcSwapAny`] instances and wants to rule the default strategy
30//! out. The strategy is chosen per instance, so enabling the feature never changes
31//! [`DefaultStrategy`] for anyone else in the dependency graph:
32//!
33//! ```rust
34//! # #[cfg(feature = "rwlock-strategy")] {
35//! use std::sync::{Arc, RwLock};
36//!
37//! use arc_swap::ArcSwapAny;
38//!
39//! let shared: ArcSwapAny<Arc<u32>, RwLock<()>> = ArcSwapAny::with_strategy(Arc::new(1), RwLock::new(()));
40//! shared.store(Arc::new(2));
41//! assert_eq!(**shared.load(), 2);
42//! # }
43//! ```
44//!
45//! Note that generally, using [`RwLock<Arc<T>>`][std::sync::RwLock] is likely to be better
46//! performance wise. So if the goal is to not use third-party unsafe code, only the one in
47//! [`std`], that is the better option. This is provided mostly for investigation and testing of
48//! [`ArcSwap`] itself or algorithms written to use [`ArcSwap`].
49//!
50//! *This is not meant to be used in production code*.
51//!
52//! [`ArcSwap`]: crate::ArcSwap
53//! [`load`]: crate::ArcSwapAny::load
54//! [`ArcSwapAny`]: crate::ArcSwapAny
55
56use core::borrow::Borrow;
57use core::sync::atomic::AtomicPtr;
58
59use crate::ref_cnt::RefCnt;
60
61pub(crate) mod hybrid;
62
63#[cfg(all(
64 feature = "internal-test-strategies",
65 feature = "experimental-thread-local"
66))]
67compile_error!("experimental-thread-local is incompatible with internal-test-strategies as it enables #[no_std]");
68
69#[cfg(all(feature = "rwlock-strategy", feature = "experimental-thread-local"))]
70compile_error!(
71 "experimental-thread-local is incompatible with rwlock-strategy as it enables #[no_std]"
72);
73
74#[cfg(feature = "rwlock-strategy")]
75mod rw_lock;
76// Do not use from outside of the crate.
77#[cfg(feature = "internal-test-strategies")]
78#[doc(hidden)]
79pub mod test_strategies;
80
81use self::hybrid::{DefaultConfig, HybridStrategy};
82
83/// The default strategy.
84///
85/// It is used by the type aliases [`ArcSwap`][crate::ArcSwap] and
86/// [`ArcSwapOption`][crate::ArcSwapOption]. Only the other strategies need to be used explicitly.
87///
88/// # Performance characteristics
89///
90/// * It is optimized for read-heavy situations, with possibly many concurrent read accesses from
91/// multiple threads. Readers don't contend each other at all.
92/// * Readers are wait-free (with the exception of at most once in `usize::MAX / 4` accesses, which
93/// is only lock-free).
94/// * Writers are lock-free.
95/// * Reclamation is exact ‒ the resource is released as soon as possible (works like RAII, not
96/// like a traditional garbage collector; can contain non-`'static` data).
97///
98/// Each thread has a limited number of fast slots (currently 8, but the exact number is not
99/// guaranteed). If it holds at most that many [`Guard`]s at once, acquiring them is fast. Once
100/// these slots are used up (by holding to these many [`Guard`]s), acquiring more of them will be
101/// slightly slower, but still wait-free.
102///
103/// If you expect to hold a lot of "handles" to the data around, or hold onto it for a long time,
104/// you may want to prefer the [`load_full`][crate::ArcSwapAny::load_full] method.
105///
106/// The speed of the fast slots is in the ballpark of locking an *uncontented* mutex. The advantage
107/// over the mutex is the stability of speed in the face of contention from other threads ‒ while
108/// the performance of mutex goes rapidly down, the slowdown of running out of held slots or heavy
109/// concurrent writer thread in the area of single-digit multiples.
110///
111/// The ballpark benchmark figures (my older computer) are around these, but you're welcome to run
112/// the benchmarks in the git repository or write your own.
113///
114/// * Load (both uncontented and contented by other loads): ~30ns
115/// * `load_full`: ~50ns uncontented, goes up a bit with other `load_full` in other threads on the
116/// same `Arc` value (~80-100ns).
117/// * Loads after running out of the slots ‒ about 10-20ns slower than `load_full`.
118/// * Stores: Dependent on number of threads, but generally low microseconds.
119/// * Loads with heavy concurrent writer (to the same `ArcSwap`): ~250ns.
120///
121/// [`load`]: crate::ArcSwapAny::load
122/// [`Guard`]: crate::Guard
123pub type DefaultStrategy = HybridStrategy<DefaultConfig>;
124
125/// Strategy for isolating instances.
126///
127/// It is similar to [`DefaultStrategy`], however the spin lock is not sharded (therefore multiple
128/// concurrent threads might get bigger hit when multiple threads have to fall back). Nevertheless,
129/// each instance has a private spin lock, not influencing the other instances. That also makes
130/// them bigger in memory.
131///
132/// The hazard pointers are still shared between all instances.
133///
134/// The purpose of this strategy is meant for cases where a single instance is going to be
135/// "tortured" a lot, so it should not overflow to other instances.
136///
137/// This too may be changed for something else (but with at least as good guarantees, primarily
138/// that other instances won't get influenced by the "torture").
139// Testing if the DefaultStrategy is good enough to replace it fully and then deprecate.
140#[doc(hidden)]
141pub type IndependentStrategy = DefaultStrategy;
142
143// TODO: When we are ready to un-seal, should these traits become unsafe?
144
145pub(crate) mod sealed {
146 use super::*;
147 use crate::as_raw::AsRaw;
148
149 pub trait Protected<T>: Borrow<T> {
150 fn into_inner(self) -> T;
151 fn from_inner(ptr: T) -> Self;
152 }
153
154 pub trait InnerStrategy<T: RefCnt> {
155 // Drop „unlocks“
156 type Protected: Protected<T>;
157 unsafe fn load(&self, storage: &AtomicPtr<T::Base>) -> Self::Protected;
158 unsafe fn wait_for_readers(&self, old: *const T::Base, storage: &AtomicPtr<T::Base>);
159 }
160
161 pub trait CaS<T: RefCnt>: InnerStrategy<T> {
162 unsafe fn compare_and_swap<C: AsRaw<T::Base>>(
163 &self,
164 storage: &AtomicPtr<T::Base>,
165 current: C,
166 new: T,
167 ) -> Self::Protected;
168 }
169}
170
171/// A strategy for protecting the reference counted pointer `T`.
172///
173/// This chooses the algorithm for how the reference counts are protected. Note that the user of
174/// the crate can't implement the trait and can't access any method; this is hopefully temporary
175/// measure to make sure the interface is not part of the stability guarantees of the crate. Once
176/// enough experience is gained with implementing various strategies, it will be un-sealed and
177/// users will be able to provide their own implementation.
178///
179/// For now, the trait works only as a bound to talk about the types that represent strategies.
180pub trait Strategy<T: RefCnt>: sealed::InnerStrategy<T> {}
181impl<T: RefCnt, S: sealed::InnerStrategy<T>> Strategy<T> for S {}
182
183/// An extension of the [`Strategy`], allowing for compare and swap operation.
184///
185/// The compare and swap operation is "advanced" and not all strategies need to support them.
186/// Therefore, it is a separate trait.
187///
188/// Similarly, it is not yet made publicly usable or implementable and works only as a bound.
189pub trait CaS<T: RefCnt>: sealed::CaS<T> {}
190impl<T: RefCnt, S: sealed::CaS<T>> CaS<T> for S {}