From c096f35224b00b48d49bdab61bedca65e2e76667 Mon Sep 17 00:00:00 2001 From: Nia Waldvogel Date: Wed, 15 Dec 2021 10:39:56 -0500 Subject: [PATCH] runtime: handle negative sleep times This change fixes the edge case where a negative sleep time is provided. When this happens, the call now returns immediately (as specified by the docs for time.Sleep). --- src/runtime/scheduler_any.go | 5 +++++ src/runtime/scheduler_none.go | 5 +++++ testdata/stdlib.go | 5 +++++ 3 files changed, 15 insertions(+) diff --git a/src/runtime/scheduler_any.go b/src/runtime/scheduler_any.go index 57fc1624..e0597dc3 100644 --- a/src/runtime/scheduler_any.go +++ b/src/runtime/scheduler_any.go @@ -1,3 +1,4 @@ +//go:build !scheduler.none // +build !scheduler.none package runtime @@ -7,6 +8,10 @@ import "internal/task" // Pause the current task for a given time. //go:linkname sleep time.Sleep func sleep(duration int64) { + if duration <= 0 { + return + } + addSleepTask(task.Current(), nanosecondsToTicks(duration)) task.Pause() } diff --git a/src/runtime/scheduler_none.go b/src/runtime/scheduler_none.go index ec83003f..b037dae0 100644 --- a/src/runtime/scheduler_none.go +++ b/src/runtime/scheduler_none.go @@ -1,9 +1,14 @@ +//go:build scheduler.none // +build scheduler.none package runtime //go:linkname sleep time.Sleep func sleep(duration int64) { + if duration <= 0 { + return + } + sleepTicks(nanosecondsToTicks(duration)) } diff --git a/testdata/stdlib.go b/testdata/stdlib.go index 55237ff6..bc59d20c 100644 --- a/testdata/stdlib.go +++ b/testdata/stdlib.go @@ -6,6 +6,7 @@ import ( "os" "strings" "syscall" + "time" ) func main() { @@ -29,6 +30,10 @@ func main() { fmt.Println("strings.IndexByte:", strings.IndexByte("asdf", 'd')) fmt.Println("strings.Replace:", strings.Replace("An example string", " ", "-", -1)) + // package time + time.Sleep(time.Millisecond) + time.Sleep(-1) // negative sleep should return immediately + // Exit the program normally. os.Exit(0) }