idle/
lib.rs

1//! Collection of idle strategies to be used by thread(s) when they have no work to perform.
2//!
3//! # Examples
4//!
5//! ```no_run
6//! use std::time::Duration;
7//! use idle::IdleStrategy;
8//!
9//! let idle = IdleStrategy::Sleep(Duration::from_millis(1));
10//! loop {
11//!     // application logic
12//!     idle.idle(0);
13//! }
14//!
15//! ```
16//!
17
18use std::hint;
19use std::time::Duration;
20
21/// Collection of idle strategies to be used by thread(s) when they have no work to perform.
22/// Requires `work_count` to be passed that for some strategies is used as hint and ignored otherwise.
23///
24/// # Examples
25///
26/// ```no_run
27/// use std::time::Duration;
28/// use idle::IdleStrategy;
29///
30/// let idle = IdleStrategy::Sleep(Duration::from_millis(1));
31/// loop {
32///     // application logic
33///     idle.idle(0);
34/// }
35/// ```
36#[derive(Debug, Copy, Clone)]
37pub enum IdleStrategy {
38    /// Does absolutely nothing. Use if you require the lowest latency at the cost of burning the CPU.
39    NoOp,
40    /// Emits machine specific instruction to signal it's in busy spin mode if no work done in the current cycle.
41    BusySpin,
42    /// Perform the `std::thread::sleep` if there is no work done in the current cycle.
43    Sleep(Duration),
44}
45
46impl IdleStrategy {
47    #[inline(always)]
48    pub fn idle(&self, work_count: usize) {
49        match *self {
50            IdleStrategy::NoOp => {}
51            IdleStrategy::BusySpin => {
52                if work_count == 0 {
53                    hint::spin_loop()
54                }
55            }
56            IdleStrategy::Sleep(duration) => {
57                if work_count == 0 {
58                    std::thread::sleep(duration)
59                }
60            }
61        }
62    }
63}