spinning_top/
relax.rs

1//! Relax strategies.
2//!
3//! Relax strategies are used when the thread cannot acquire a spinlock.
4
5/// A relax strategy.
6///
7/// `Relax` types are used to relax the current thread during contention.
8pub trait Relax: Default {
9    /// Relaxes the current thread.
10    fn relax(&mut self);
11}
12
13/// Rapid spinning.
14///
15/// This emits [`core::hint::spin_loop`].
16#[derive(Default, Debug)]
17pub struct Spin;
18
19impl Relax for Spin {
20    #[inline]
21    fn relax(&mut self) {
22        core::hint::spin_loop();
23    }
24}
25
26/// Exponential backoff.
27///
28/// This performs exponential backoff to avoid unnecessarily stressing the cache.
29//Adapted from <https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.16/crossbeam-utils/src/backoff.rs>.
30#[derive(Default, Debug)]
31pub struct Backoff {
32    step: u8,
33}
34
35impl Backoff {
36    const YIELD_LIMIT: u8 = 10;
37}
38
39impl Relax for Backoff {
40    #[inline]
41    fn relax(&mut self) {
42        for _ in 0..1_u16 << self.step {
43            core::hint::spin_loop();
44        }
45
46        if self.step <= Self::YIELD_LIMIT {
47            self.step += 1;
48        }
49    }
50}