aboutsummaryrefslogtreecommitdiff
path: root/src/context/example_test.go
diff options
context:
space:
mode:
authorBryan C. Mills <bcmills@google.com>2023-01-10 11:49:37 -0500
committerGopher Robot <gobot@golang.org>2023-01-25 21:12:45 +0000
commit3d49b683c6095a9a2681e84f05adfbb8d82882e8 (patch)
tree6c4d700443a90cb1eb246b51e6d7438f72eb09ed /src/context/example_test.go
parent6e82febaf0ca737e82cc3f53de7245101821821c (diff)
downloadgo-3d49b683c6095a9a2681e84f05adfbb8d82882e8.tar.xz
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>
Diffstat (limited to 'src/context/example_test.go')
-rw-r--r--src/context/example_test.go10
1 files changed, 6 insertions, 4 deletions
diff --git a/src/context/example_test.go b/src/context/example_test.go
index 72ac5d2e49..7779f5f1b3 100644
--- a/src/context/example_test.go
+++ b/src/context/example_test.go
@@ -12,6 +12,8 @@ import (
const shortDuration = 1 * time.Millisecond // a reasonable duration to block in an example
+var neverReady = make(chan struct{}) // never closed
+
// This example demonstrates the use of a cancelable context to prevent a
// goroutine leak. By the end of the example function, the goroutine started
// by gen will return without leaking.
@@ -66,8 +68,8 @@ func ExampleWithDeadline() {
defer cancel()
select {
- case <-time.After(1 * time.Second):
- fmt.Println("overslept")
+ case <-neverReady:
+ fmt.Println("ready")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
@@ -85,8 +87,8 @@ func ExampleWithTimeout() {
defer cancel()
select {
- case <-time.After(1 * time.Second):
- fmt.Println("overslept")
+ case <-neverReady:
+ fmt.Println("ready")
case <-ctx.Done():
fmt.Println(ctx.Err()) // prints "context deadline exceeded"
}