use crate::thread_parker;
use core::hint::spin_loop;
#[inline]
fn cpu_relax(iterations: u32) {
for _ in 0..iterations {
spin_loop()
}
}
#[derive(Default)]
pub struct SpinWait {
counter: u32,
}
impl SpinWait {
#[inline]
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn reset(&mut self) {
self.counter = 0;
}
#[inline]
pub fn spin(&mut self) -> bool {
if self.counter >= 10 {
return false;
}
self.counter += 1;
if self.counter <= 3 {
cpu_relax(1 << self.counter);
} else {
thread_parker::thread_yield();
}
true
}
#[inline]
pub fn spin_no_yield(&mut self) {
self.counter += 1;
if self.counter > 10 {
self.counter = 10;
}
cpu_relax(1 << self.counter);
}
}