]> Cypherpunks repositories - gostls13.git/commitdiff
context: cancel the context in ExampleWithTimeout, with explanation
authorAlan Donovan <adonovan@google.com>
Thu, 30 Jun 2016 18:55:01 +0000 (14:55 -0400)
committerAlan Donovan <adonovan@google.com>
Thu, 30 Jun 2016 19:56:02 +0000 (19:56 +0000)
Fixes #16230

Change-Id: Ibb10234a6c3ab8bd0cfd93c2ebe8cfa66f80f6b0
Reviewed-on: https://go-review.googlesource.com/24682
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
src/context/withtimeout_test.go

index 2aea303bedcb8751fba26b394b194954470f6cf6..a3e8979c8c3e9b077cf9561f0d9d8856e8f17cfb 100644 (file)
@@ -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
 }