Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #16 from mkroening/backoff
feat: add backoff feature
- Loading branch information
Showing
3 changed files
with
191 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
//! Relax strategies. | ||
//! | ||
//! Relax strategies are used when the thread cannot acquire a spinlock. | ||
|
||
/// A relax strategy. | ||
/// | ||
/// `Relax` types are used to relax the current thread during contention. | ||
pub trait Relax: Default { | ||
/// Relaxes the current thread. | ||
fn relax(&mut self); | ||
} | ||
|
||
/// Rapid spinning. | ||
/// | ||
/// This emits [`core::hint::spin_loop`]. | ||
#[derive(Default, Debug)] | ||
pub struct Spin; | ||
|
||
impl Relax for Spin { | ||
#[inline] | ||
fn relax(&mut self) { | ||
core::hint::spin_loop(); | ||
} | ||
} | ||
|
||
/// Exponential backoff. | ||
/// | ||
/// This performs exponential backoff to avoid unnecessarily stressing the cache. | ||
//Adapted from <https://github.com/crossbeam-rs/crossbeam/blob/crossbeam-utils-0.8.16/crossbeam-utils/src/backoff.rs>. | ||
#[derive(Default, Debug)] | ||
pub struct Backoff { | ||
step: u8, | ||
} | ||
|
||
impl Backoff { | ||
const YIELD_LIMIT: u8 = 10; | ||
} | ||
|
||
impl Relax for Backoff { | ||
#[inline] | ||
fn relax(&mut self) { | ||
for _ in 0..1_u16 << self.step { | ||
core::hint::spin_loop(); | ||
} | ||
|
||
if self.step <= Self::YIELD_LIMIT { | ||
self.step += 1; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters