use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard, TryLockError}; /// The locks counted. #[derive(Clone, Copy)] pub(crate) enum Kind { Actor, Control, TableRead, TableWrite, Stacks, } const KINDS: usize = 5; /// What each [`Kind`] is called in the report. pub(crate) const NAMES: [&str; KINDS] = [ "actor locks", "control lock", "actor table (read)", "actor table (write)", "stack pool", ]; static TAKEN: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; static CONTENDED: [AtomicU64; KINDS] = [const { AtomicU64::new(0) }; KINDS]; thread_local! { // (taken, contended) per kind. Read and written only between // suspensions. static MINE: std::cell::Cell<[(u64, u64); KINDS]> = const { std::cell::Cell::new([(0, 0); KINDS]) }; } fn count(kind: Kind, contended: bool) { let mut mine = MINE.get(); let (taken, found) = &mut mine[kind as usize]; *taken += 1; *found += u64::from(contended); MINE.set(mine); } fn counted(kind: Kind, tried: Result>, wait: impl FnOnce() -> G) -> G { match tried { Ok(guard) => { count(kind, false); guard } Err(TryLockError::WouldBlock) => { count(kind, true); wait() } Err(TryLockError::Poisoned(_)) => panic!("louise: scheduler poisoned"), } } pub(super) fn lock(kind: Kind, m: &Mutex) -> MutexGuard<'_, T> { counted(kind, m.try_lock(), || { m.lock().expect("louise: scheduler poisoned") }) } pub(super) fn read(m: &RwLock) -> RwLockReadGuard<'_, T> { counted(Kind::TableRead, m.try_read(), || { m.read().expect("louise: scheduler poisoned") }) } pub(super) fn write(m: &RwLock) -> RwLockWriteGuard<'_, T> { counted(Kind::TableWrite, m.try_write(), || { m.write().expect("louise: scheduler poisoned") }) } /// Add this thread's counts to the totals. pub(super) fn flush() { for (i, (taken, contended)) in MINE.replace([(0, 0); KINDS]).into_iter().enumerate() { TAKEN[i].fetch_add(taken, Ordering::Relaxed); CONTENDED[i].fetch_add(contended, Ordering::Relaxed); } } /// (taken, contended) per kind, once the scheduler threads stopped. pub(crate) fn totals() -> [(u64, u64); KINDS] { std::array::from_fn(|i| { ( TAKEN[i].load(Ordering::Relaxed), CONTENDED[i].load(Ordering::Relaxed), ) }) }