From f139b9ae0e8d98dc98e1dec6bb0fc427d36ccefa Mon Sep 17 00:00:00 2001 From: aur-build Date: Thu, 19 Nov 2026 20:27:26 +0000 Subject: time: the virtual clock freezes, it does not race Advancing the clock on every wait made virtual time outrun real work: a build taking a few hundred ms would burn forty ticks and expire its own lease. Under a virtual clock a wait now costs a yield and the clock only moves when a test moves it with time::advance, so a frozen lease stays frozen however fast the loop runs. --- src/time.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/time.rs b/src/time.rs index 1ffc116..5ce1751 100644 --- a/src/time.rs +++ b/src/time.rs @@ -77,7 +77,7 @@ pub fn secs_ahead(secs: i64) -> String { /// before the wait finished, so a control loop can leave instead of doing one /// more pass. pub fn wait(d: Duration, slice: Duration, stop: &AtomicBool) -> bool { - if clock::advance(d) { + if clock::virtual_sleep() { return !stop.load(Ordering::SeqCst); } let mut left = d; @@ -93,7 +93,7 @@ pub fn wait(d: Duration, slice: Duration, stop: &AtomicBool) -> bool { } pub fn sleep(d: Duration) { - if clock::advance(d) { + if clock::virtual_sleep() { return; } std::thread::sleep(d); @@ -120,6 +120,13 @@ pub fn virtual_now() -> Option> { clock::now() } +/// Move the frozen clock along, so a control loop can be made to believe a tick, +/// a lease or a cooldown has elapsed without anything waiting for it. +#[cfg(feature = "test-support")] +pub fn advance(d: Duration) { + clock::advance(d) +} + #[cfg(feature = "test-support")] mod clock { use super::*; @@ -162,19 +169,24 @@ mod clock { *lock(&AT) } - /// Returns true when the wait was virtual: the clock moved, no wall time did. - pub fn advance(d: Duration) -> bool { + /// Returns true when this thread is on the virtual clock: the wait cost a + /// yield and no wall time. The clock does not move by itself - a test moves it + /// with `advance`, so a frozen lease stays frozen however fast the loop runs. + pub fn virtual_sleep() -> bool { if !ON.get() { return false; } + // A control loop that never blocks still needs to let its caller run. + std::thread::yield_now(); + true + } + + pub fn advance(d: Duration) { let mut at = lock(&AT); if let Some(t) = *at { let step = chrono::TimeDelta::from_std(d).unwrap_or_else(|_| chrono::TimeDelta::zero()); *at = Some(t + step); } - // A control loop that never blocks still needs to let its caller run. - std::thread::yield_now(); - true } pub fn wrap(f: F) -> impl FnOnce() -> T @@ -195,7 +207,7 @@ mod clock { use super::*; #[inline(always)] - pub fn advance(_d: Duration) -> bool { + pub fn virtual_sleep() -> bool { false } -- cgit v1.2.3