Struct conquer_util::BackOff
source · [−]pub struct BackOff { /* private fields */ }
Expand description
A type for exponential back-off in tight loops.
In concurrent environments it can often be beneficial to back off from accessing shared variables in loops in order to reduce contention and improve performance for all participating threads by spinning for a short amount of time.
Implementations
Creates a new BackOff
instance with a fixed exponential back-off
strategy.
Spin once.
This is a convenience wrapper for
spin_loop_hint
, but will never
compile to only a nop on platforms, that don’t offer a wait
-like CPU
instruction, but will instead result in an empty function call.
Spins for a bounded number of steps
On CPUs that support such instructions, in each step the processor will
be instructed to deliberately slow down, e.g. using the pause
instruction on x86, which can also save energy.
Each invocation of this method exponentially increases the number of
spin cycles until a point at which further spinning is no longer
advisable and other strategies, such as yielding the current thread to
the OS, should be preferred.
From this point on, the number of spin cycles remains constant with each
further invocation of spin
.
Whether this point has been reached can be determined through the
advise_yield
method.
Returns true
if further spinning is not advisable and other means such
as voluntarily yielding the current thread could be more efficient.
Examples
Back-off exponentially until it is no longer advisable.
use conquer_util::BackOff;
let mut backoff = BackOff::new();
while !backoff.advise_yield() {
backoff.spin();
}
Repedeatly check a condition and either back-off exponentially or yield the current thread, if the condition is not yet met.
use conquer_util::BackOff;
let mut backoff = BackOff::new();
while !cond {
if backoff.advise_yield() {
std::thread::yield_now();
} else {
backoff.spin();
}
}
Notes
On an Intel(R) i5 with 2.60 GHz a full back-off cycle has been measured to take approximately 750 nanoseconds