diff options
author | Alan Donovan <adonovan@google.com> | 2016-06-30 14:55:01 -0400 |
---|---|---|
committer | Alan Donovan <adonovan@google.com> | 2016-06-30 19:56:02 +0000 |
commit | fc12bb263683e43c0b93eb00071f894f5cfcc772 (patch) | |
tree | 4efa4e42cab159b2d52b88922bb0b0f01215ca16 /src/context | |
parent | 9c8809f82aa59e0725e93cffb03de863e61cbbae (diff) | |
download | go-git-fc12bb263683e43c0b93eb00071f894f5cfcc772.tar.gz |
context: cancel the context in ExampleWithTimeout, with explanation
Fixes #16230
Change-Id: Ibb10234a6c3ab8bd0cfd93c2ebe8cfa66f80f6b0
Reviewed-on: https://go-review.googlesource.com/24682
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Diffstat (limited to 'src/context')
-rw-r--r-- | src/context/withtimeout_test.go | 10 |
1 files changed, 9 insertions, 1 deletions
diff --git a/src/context/withtimeout_test.go b/src/context/withtimeout_test.go index 2aea303bed..a3e8979c8c 100644 --- a/src/context/withtimeout_test.go +++ b/src/context/withtimeout_test.go @@ -13,13 +13,21 @@ import ( func ExampleWithTimeout() { // Pass a context with a timeout to tell a blocking function that it // should abandon its work after the timeout elapses. - ctx, _ := context.WithTimeout(context.Background(), 50*time.Millisecond) + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + select { case <-time.After(1 * time.Second): fmt.Println("overslept") case <-ctx.Done(): fmt.Println(ctx.Err()) // prints "context deadline exceeded" } + + // Even though ctx should have expired already, it is good + // practice to call its cancelation function in any case. + // Failure to do so may keep the context and its parent alive + // longer than necessary. + cancel() + // Output: // context deadline exceeded } |