Browse Source

context: sync ExampleWithTimeout with std lib context

CL 47095 applied a change to ExampleWithTimeout to resolve test
flakiness. This change deviated ExampleWithTimeout further away
from the ExampleWithTimeout in standard library's context package.

There was a minor issue spotted in code review. Instead of attempting
to resolve it here, it's better to use the version of ExampleWithTimeout
from standard library that doesn't have the issue, and reduce
maintenance.

Change-Id: I3da9d7f7c35b33b52635df4c61058cb0b8ae95d9
Reviewed-on: https://go-review.googlesource.com/47212
Run-TryBot: Dmitri Shuralyov <shurcool@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Dmitri Shuralyov 8 years ago
parent
commit
1f9224279e
1 changed files with 7 additions and 5 deletions
  1. 7 5
      context/withtimeout_test.go

+ 7 - 5
context/withtimeout_test.go

@@ -11,19 +11,21 @@ import (
 	"golang.org/x/net/context"
 	"golang.org/x/net/context"
 )
 )
 
 
-var workComplete <-chan int
-
+// This example passes a context with a timeout to tell a blocking function that
+// it should abandon its work after the timeout elapses.
 func ExampleWithTimeout() {
 func ExampleWithTimeout() {
 	// Pass a context with a timeout to tell a blocking function that it
 	// Pass a context with a timeout to tell a blocking function that it
 	// should abandon its work after the timeout elapses.
 	// should abandon its work after the timeout elapses.
-	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
+	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+	defer cancel()
+
 	select {
 	select {
-	case <-workComplete:
-		cancel()
+	case <-time.After(1 * time.Second):
 		fmt.Println("overslept")
 		fmt.Println("overslept")
 	case <-ctx.Done():
 	case <-ctx.Done():
 		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
 		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
 	}
 	}
+
 	// Output:
 	// Output:
 	// context deadline exceeded
 	// context deadline exceeded
 }
 }