[−][src]Struct crossbeam_utils::Backoff
Performs exponential backoff in spin loops.
Backing off in spin loops reduces contention and improves overall performance.
This primitive can execute YIELD and PAUSE instructions, yield the current thread to the OS scheduler, and tell when is a good time to block the thread using a different synchronization mechanism. Each step of the back off procedure takes roughly twice as long as the previous step.
Examples
Backing off in a lock-free loop:
use crossbeam_utils::Backoff; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; fn fetch_mul(a: &AtomicUsize, b: usize) -> usize { let backoff = Backoff::new(); loop { let val = a.load(SeqCst); if a.compare_and_swap(val, val.wrapping_mul(b), SeqCst) == val { return val; } backoff.spin(); } }
Waiting for an AtomicBool
to become true
:
use crossbeam_utils::Backoff; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; fn spin_wait(ready: &AtomicBool) { let backoff = Backoff::new(); while !ready.load(SeqCst) { backoff.snooze(); } }
Waiting for an AtomicBool
to become true
and parking the thread after a long wait.
Note that whoever sets the atomic variable to true
must notify the parked thread by calling
unpark()
:
use crossbeam_utils::Backoff; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; use std::thread; fn blocking_wait(ready: &AtomicBool) { let backoff = Backoff::new(); while !ready.load(SeqCst) { if backoff.is_completed() { thread::park(); } else { backoff.snooze(); } } }
Methods
impl Backoff
[src][−]
pub fn new() -> Self
[src][+]
pub fn reset(&self)
[src][+]
pub fn spin(&self)
[src][+]
pub fn snooze(&self)
[src][+]
pub fn is_completed(&self) -> bool
[src][+]
Trait Implementations
Auto Trait Implementations
Blanket Implementations
impl<T> From for T
[src][+]
impl<T, U> Into for T where
U: From<T>,
[src][+]
U: From<T>,
impl<T, U> TryFrom for T where
U: Into<T>,
[src][+]
U: Into<T>,
impl<T> Borrow for T where
T: ?Sized,
[src][+]
T: ?Sized,
impl<T> Any for T where
T: 'static + ?Sized,
[src][+]
T: 'static + ?Sized,
impl<T> BorrowMut for T where
T: ?Sized,
[src][+]
T: ?Sized,
impl<T, U> TryInto for T where
U: TryFrom<T>,
[src][+]
U: TryFrom<T>,