//! Parking scheduler threads (ADR 0004, Revision 8): each thread sleeps on //! its own [`Parker`], so work for one thread wakes that thread alone, and //! [`Idle`] wakes a parked thread to look for work only when no thread is //! looking already, as Go's `wakep` and Tokio's searching workers do. //! Checked with loom (`RUSTFLAGS="--cfg loom" cargo test -p louise_rt //! --release --lib park`). //! //! **Searching.** A thread with nothing of its own to run may search the //! others' queues, if fewer than half the threads awake are searching //! ([`Idle::try_search`]). A push that leaves work for others to take //! calls [`Idle::notify_one`], which wakes a parked thread only if none is //! searching, and counts it as searching on its behalf, so a burst of //! pushes wakes one thread, not one each. A searcher that finds work stops //! searching; if it was the last, it calls `notify_one` again, so wake-ups //! spread one at a time while work remains. //! //! **No lost wake-up.** A thread about to park first lists itself //! ([`Idle::announce`]), then stops searching, then re-checks for work; //! a pusher publishes its work, then reads the count of searchers. A //! `SeqCst` fence on each side, between its write and its read, means //! one of them sees the other: the parker finds the work, or the pusher //! finds no searcher and the parker listed, and wakes it. A wake-up for one //! thread ([`Idle::unpark`]) sets its parker's token, which a later //! [`Parker::park`] consumes without sleeping. #[cfg(loom)] use loom::sync::{ Condvar, Mutex, atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering, fence}, }; use std::time::Duration; #[cfg(not(loom))] use std::sync::{ Condvar, Mutex, atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering, fence}, }; const AWAKE: u8 = 0; const PARKED: u8 = 1; const NOTIFIED: u8 = 2; /// One thread's place to sleep, with a wake-up token (as `std::thread`'s /// park and unpark): an unpark before the park makes the park return at /// once. pub(crate) struct Parker { state: AtomicU8, lock: Mutex<()>, wake: Condvar, } impl Parker { pub(crate) fn new() -> Self { Parker { state: AtomicU8::new(AWAKE), lock: Mutex::new(()), wake: Condvar::new(), } } /// Sleep until unparked, or `timeout` passes. Returns at once if /// unparked since the last park. pub(crate) fn park(&self, timeout: Option) { if self .state .compare_exchange(NOTIFIED, AWAKE, Ordering::SeqCst, Ordering::SeqCst) .is_ok() { return; } let mut guard = self.lock.lock().expect("louise: parker poisoned"); if self .state .compare_exchange(AWAKE, PARKED, Ordering::SeqCst, Ordering::SeqCst) .is_err() { // Unparked meanwhile. self.state.store(AWAKE, Ordering::SeqCst); return; } loop { guard = match timeout { None => self.wake.wait(guard).expect("louise: parker poisoned"), Some(t) => { let (guard, waited) = self .wake .wait_timeout(guard, t) .expect("louise: parker poisoned"); if waited.timed_out() { self.state.store(AWAKE, Ordering::SeqCst); return; } guard } }; if self .state .compare_exchange(NOTIFIED, AWAKE, Ordering::SeqCst, Ordering::SeqCst) .is_ok() { return; } } } /// Wake the thread, or make its next park return at once. pub(crate) fn unpark(&self) { if self.state.swap(NOTIFIED, Ordering::SeqCst) == PARKED { // Taken so the notification cannot fall between the parker's // check of `state` and its wait. drop(self.lock.lock().expect("louise: parker poisoned")); self.wake.notify_one(); } } } /// The scheduler's threads as parked or searching. pub(crate) struct Idle { parkers: Box<[Parker]>, /// Set by [`Idle::notify_one`] for the thread it wakes: that thread is /// already counted in `searching`. handed: Box<[AtomicBool]>, searching: AtomicUsize, /// Threads listed as parked, most recent last. parked: Mutex>, num_parked: AtomicUsize, } impl Idle { pub(crate) fn new(threads: usize) -> Self { Idle { parkers: (0..threads).map(|_| Parker::new()).collect(), handed: (0..threads).map(|_| AtomicBool::new(false)).collect(), searching: AtomicUsize::new(0), parked: Mutex::new(Vec::with_capacity(threads)), num_parked: AtomicUsize::new(0), } } fn threads(&self) -> usize { self.parkers.len() } /// Start searching other threads' queues, unless half the threads awake /// are searching already. pub(crate) fn try_search(&self) -> bool { let awake = self.threads() - self.num_parked.load(Ordering::SeqCst); let searching = self.searching.load(Ordering::SeqCst); if searching > 0 && 2 * searching >= awake { return false; } self.searching.fetch_add(1, Ordering::SeqCst); true } /// Stop searching; returns whether this was the last searcher. pub(crate) fn stop_searching(&self) -> bool { self.searching.fetch_sub(1, Ordering::SeqCst) == 1 } /// Work was published that another thread could take: wake a parked /// thread to search for it, unless one is searching already. pub(crate) fn notify_one(&self) { fence(Ordering::SeqCst); if self.searching.load(Ordering::SeqCst) > 0 || self.num_parked.load(Ordering::SeqCst) == 0 { return; } let woken = { let mut parked = self.parked.lock().expect("louise: idle poisoned"); if self.searching.load(Ordering::SeqCst) > 0 { return; } let woken = parked.pop(); if let Some(thread) = woken { self.num_parked.fetch_sub(1, Ordering::SeqCst); self.searching.fetch_add(1, Ordering::SeqCst); // Under the lock: `unlist` reads it under the same lock, so // a thread off the list always sees whether it was handed. self.handed[thread].store(true, Ordering::SeqCst); } woken }; if let Some(thread) = woken { self.parkers[thread].unpark(); } } /// Wake thread `thread`: work was queued for it alone. pub(crate) fn unpark(&self, thread: usize) { self.parkers[thread].unpark(); } /// Wake every thread (the scheduler finished, or needs an idle thread). pub(crate) fn unpark_all(&self) { for parker in &self.parkers { parker.unpark(); } } /// Wake one parked thread, searching or not (an idle thread is needed). pub(crate) fn unpark_any(&self) { let woken = { let mut parked = self.parked.lock().expect("louise: idle poisoned"); let woken = parked.pop(); if woken.is_some() { self.num_parked.fetch_sub(1, Ordering::SeqCst); } woken }; if let Some(thread) = woken { self.parkers[thread].unpark(); } } /// List `thread` as parked, before it re-checks for work and parks. pub(crate) fn announce(&self, thread: usize) { let mut parked = self.parked.lock().expect("louise: idle poisoned"); parked.push(thread); self.num_parked.fetch_add(1, Ordering::SeqCst); } /// After [`Idle::announce`] (and `stop_searching` if it searched), /// before re-checking for work. pub(crate) fn fence(&self) { fence(Ordering::SeqCst); } /// Sleep `thread` (announced) until woken or `timeout`. Returns whether /// it woke as a searcher ([`Idle::notify_one`] counted it). pub(crate) fn park(&self, thread: usize, timeout: Option) -> bool { self.parkers[thread].park(timeout); self.unlist(thread) } /// Take `thread` off the parked list, if still on it (it found work /// before parking, or woke for another reason than `notify_one`). /// Returns whether `notify_one` woke it as a searcher. pub(crate) fn unlist(&self, thread: usize) -> bool { let mut parked = self.parked.lock().expect("louise: idle poisoned"); if let Some(at) = parked.iter().rposition(|&t| t == thread) { parked.remove(at); self.num_parked.fetch_sub(1, Ordering::SeqCst); } self.handed[thread].swap(false, Ordering::SeqCst) } /// Threads listed as parked now. #[cfg(test)] pub(crate) fn parked(&self) -> usize { self.num_parked.load(Ordering::SeqCst) } /// Threads searching now. #[cfg(test)] pub(crate) fn searching(&self) -> usize { self.searching.load(Ordering::SeqCst) } } #[cfg(all(test, loom))] mod loom_models { use super::*; use loom::sync::Arc; use loom::sync::atomic::AtomicUsize; use loom::thread; /// An unpark before or during a park is never lost. #[test] fn unpark_wakes_a_park() { loom::model(|| { let parker = Arc::new(Parker::new()); let flag = Arc::new(AtomicUsize::new(0)); let waker = { let (parker, flag) = (parker.clone(), flag.clone()); thread::spawn(move || { flag.store(1, Ordering::SeqCst); parker.unpark(); }) }; while flag.load(Ordering::SeqCst) == 0 { parker.park(None); } waker.join().unwrap(); }); } /// A thread parking for lack of work, against a push of work and a /// `notify_one`: the thread finds the work, or is woken for it. #[test] fn notify_one_reaches_a_parking_searcher() { loom::model(|| { let idle = Arc::new(Idle::new(2)); let work = Arc::new(AtomicUsize::new(0)); let pusher = { let (idle, work) = (idle.clone(), work.clone()); thread::spawn(move || { work.store(1, Ordering::SeqCst); idle.notify_one(); }) }; // Thread 1: searching, found nothing, parks. assert!(idle.try_search()); loop { idle.announce(1); let _ = idle.stop_searching(); idle.fence(); if work.load(Ordering::SeqCst) == 1 { // `notify_one` may have handed it the search already. if idle.unlist(1) { let _ = idle.stop_searching(); } break; } if idle.park(1, None) { // Woken to search. if work.load(Ordering::SeqCst) == 1 { let _ = idle.stop_searching(); break; } } else { assert!(idle.try_search()); } } pusher.join().unwrap(); assert_eq!(idle.searching(), 0); }); } /// Work for one thread, against that thread parking: it is woken. #[test] fn unpark_reaches_its_thread() { loom::model(|| { let idle = Arc::new(Idle::new(2)); let inbound = Arc::new(AtomicUsize::new(0)); let pusher = { let (idle, inbound) = (idle.clone(), inbound.clone()); thread::spawn(move || { inbound.store(1, Ordering::SeqCst); idle.unpark(0); }) }; while inbound.load(Ordering::SeqCst) == 0 { idle.announce(0); idle.fence(); if inbound.load(Ordering::SeqCst) == 1 { let _ = idle.unlist(0); break; } let _ = idle.park(0, None); } pusher.join().unwrap(); }); } } #[cfg(all(test, not(loom)))] mod tests { use super::*; #[test] fn notify_one_wakes_one_searcher_at_a_time() { let idle = Idle::new(4); idle.announce(1); idle.announce(2); idle.notify_one(); assert_eq!(idle.searching(), 1, "the woken thread counts as searching"); idle.notify_one(); assert_eq!(idle.searching(), 1, "no second thread while one searches"); assert!(idle.park(2, None), "woke as a searcher"); assert!(idle.stop_searching()); assert!(!idle.unlist(1), "still parked, not handed"); } #[test] fn at_most_half_the_awake_threads_search() { let idle = Idle::new(4); assert!(idle.try_search()); assert!(idle.try_search()); assert!(!idle.try_search(), "two of four"); idle.announce(3); assert!(!idle.try_search(), "two of three awake"); } #[test] fn an_early_unpark_makes_the_park_return() { let parker = Parker::new(); parker.unpark(); parker.park(None); parker.park(Some(Duration::from_millis(1))); } }