//! A hand-off between scheduler threads (ADR 0004, Revision 2), as a small //! type that the scheduler uses and loom models check //! (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt --release --lib handoff`). //! //! [`RunState`]: an actor is woken while another thread runs it. A //! wake-up queues the actor only if it is suspended and not queued yet; //! otherwise the thread running it queues it when it yields. No wake-up is //! lost, none is doubled. Its races with messages, timers and kills are //! modelled in `otp`, with the mailbox. //! //! The other hand-off, a thread going to sleep while another pushes work, //! is in `park` (Revision 8). #[cfg(loom)] pub(crate) use loom::sync::atomic::{AtomicUsize, Ordering}; #[cfg(not(loom))] pub(crate) use std::sync::atomic::{AtomicUsize, Ordering}; /// Where an actor is, as the scheduler sees it. Kept under the actor's /// lock, next to its wait state. pub(crate) enum Run { /// Suspended (or not started): its fiber. Suspended(F), /// A thread is running it. Running, /// Its fiber returned. Finished, } pub(crate) struct RunState { run: Run, /// In a run queue (at most once). queued: bool, } impl RunState { pub(crate) fn new(fiber: F) -> Self { RunState { run: Run::Suspended(fiber), queued: false, } } /// The actor became ready: whether the caller must queue it. pub(crate) fn wake(&mut self) -> bool { if matches!(self.run, Run::Suspended(_)) && !self.queued { self.queued = true; return true; } false } /// Mark a new actor as queued (it is pushed right after). pub(crate) fn queue_new(&mut self) { debug_assert!(!self.queued); self.queued = true; } /// Taken from a run queue: its fiber, to resume. pub(crate) fn start(&mut self) -> Option { self.queued = false; match std::mem::replace(&mut self.run, Run::Running) { Run::Suspended(f) => Some(f), other => { self.run = other; None } } } /// It yielded, `ready` or waiting: whether the caller must queue it /// again (it was preempted, or woken while it ran). pub(crate) fn stop(&mut self, fiber: F, ready: bool) -> bool { self.run = Run::Suspended(fiber); self.wake_if(ready) } fn wake_if(&mut self, ready: bool) -> bool { ready && self.wake() } /// The fiber of an actor that is suspended and not queued: nothing /// resumes it while the caller holds the actor's lock. pub(crate) fn idle_fiber(&mut self) -> Option<&mut F> { match &mut self.run { Run::Suspended(f) if !self.queued => Some(f), _ => None, } } pub(crate) fn finish(&mut self) { self.run = Run::Finished; self.queued = false; } } #[cfg(test)] mod tests { use super::*; #[test] fn run_state_transitions() { let mut r = RunState::new(1); assert!(r.wake()); assert!(!r.wake(), "queued at most once"); assert_eq!(r.start(), Some(1)); assert!(!r.wake(), "running: its thread requeues it"); assert!(r.stop(1, true), "woken while running"); assert_eq!(r.start(), Some(1)); assert!(!r.stop(1, false), "parked"); r.finish(); assert!(!r.wake(), "finished"); } }