Skip to content

Commit

Permalink
fix: make sleep wait for at least 1ms (#199)
Browse files Browse the repository at this point in the history
Signed-off-by: Runji Wang <wangrunji0408@163.com>
  • Loading branch information
wangrunji0408 committed Mar 18, 2024
1 parent ca93352 commit 3039115
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## madsim [0.2.26] - 2024-03-18

### Fixed

- `sleep` and `sleep_until` now sleep for at least 1ms to be consistent with tokio's behavior.

## rdkafka [0.3.3] - 2024-02-28

### Changed
Expand Down
4 changes: 2 additions & 2 deletions madsim/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "madsim"
version = "0.2.25"
version = "0.2.26"
edition = "2021"
authors = ["Runji Wang <wangrunji0408@163.com>"]
description = "Deterministic Simulator for distributed systems."
Expand Down Expand Up @@ -62,7 +62,7 @@ tokio-util = { version = "0.7", features = ["codec"] }
[dev-dependencies]
criterion = "0.5"
structopt = "0.3"
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util"] }

[[bench]]
name = "rpc"
Expand Down
16 changes: 15 additions & 1 deletion madsim/src/sim/time/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,20 @@ impl TimeHandle {
}

/// Waits until `duration` has elapsed.
///
/// It will sleep for at least 1ms to be consistent with the behavior of `tokio::time::sleep`.
pub fn sleep(&self, duration: Duration) -> Sleep {
self.sleep_until(self.clock.now_instant() + duration)
}

/// Waits until `deadline` is reached.
///
/// It will sleep for at least 1ms to be consistent with the behavior of `tokio::time::sleep_until`.
pub fn sleep_until(&self, deadline: Instant) -> Sleep {
let min_deadline = self.clock.now_instant() + Duration::from_millis(1);
Sleep {
handle: self.clone(),
deadline,
deadline: deadline.max(min_deadline),
}
}

Expand Down Expand Up @@ -233,6 +238,15 @@ mod tests {
fn time() {
let runtime = Runtime::new();
runtime.block_on(async {
// sleep for at least 1ms
let t0 = Instant::now();
sleep(Duration::default()).await;
assert!(t0.elapsed() >= Duration::from_millis(1));

let t0 = Instant::now();
sleep_until(t0).await;
assert!(t0.elapsed() >= Duration::from_millis(1));

let t0 = Instant::now();

sleep(Duration::from_secs(1)).await;
Expand Down

0 comments on commit 3039115

Please sign in to comment.