Skip to content

Commit 3d49b68

Browse files
Bryan C. Millsgopherbot
authored andcommitted
context: eliminate arbitrary timeouts in examples
ExampleWithDeadline and ExampleWithTimeout used an arbitrary 1-second timeout for a “blocked” select case, which could fail if the test goroutine happens to be descheduled for over a second, or perhaps if an NTP synchronization happens to jump by a second at just the right time. Either case is plausible, especially on a heavily-loaded or slow machine (as is often the case for builders for unusual ports). Instead of an arbitrary timeout, use a “ready” channel that is never actually ready. Fixes #57594. Change-Id: I9ff68f50b041a3382e7b267c28c5259e886a9d23 Reviewed-on: https://go-review.googlesource.com/c/go/+/460999 TryBot-Result: Gopher Robot <gobot@golang.org> Auto-Submit: Bryan Mills <bcmills@google.com> Reviewed-by: Ian Lance Taylor <iant@google.com> Reviewed-by: Sameer Ajmani <sameer@golang.org> Run-TryBot: Bryan Mills <bcmills@google.com>
1 parent 6e82feb commit 3d49b68

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/context/example_test.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import (
1212

1313
const shortDuration = 1 * time.Millisecond // a reasonable duration to block in an example
1414

15+
var neverReady = make(chan struct{}) // never closed
16+
1517
// This example demonstrates the use of a cancelable context to prevent a
1618
// goroutine leak. By the end of the example function, the goroutine started
1719
// by gen will return without leaking.
@@ -66,8 +68,8 @@ func ExampleWithDeadline() {
6668
defer cancel()
6769

6870
select {
69-
case <-time.After(1 * time.Second):
70-
fmt.Println("overslept")
71+
case <-neverReady:
72+
fmt.Println("ready")
7173
case <-ctx.Done():
7274
fmt.Println(ctx.Err())
7375
}
@@ -85,8 +87,8 @@ func ExampleWithTimeout() {
8587
defer cancel()
8688

8789
select {
88-
case <-time.After(1 * time.Second):
89-
fmt.Println("overslept")
90+
case <-neverReady:
91+
fmt.Println("ready")
9092
case <-ctx.Done():
9193
fmt.Println(ctx.Err()) // prints "context deadline exceeded"
9294
}

0 commit comments

Comments
 (0)