diff options
author | Bryan C. Mills <bcmills@google.com> | 2015-02-10 18:40:36 -0500 |
---|---|---|
committer | Bryan Mills <bcmills@google.com> | 2015-02-12 17:18:52 +0000 |
commit | 59b0df9b1f7abda5aab0495ee54f408daf182ce7 (patch) | |
tree | eeae8755dcf254abd4c1d71e5e00fca585b430c3 | |
parent | ec18079348e79eb393866e87d402a1a8cc580d7f (diff) | |
download | net-master.tar.gz |
net/context: Don't leak goroutines in Done example.HEADgradle_1.3.1gradle_1.3.0-beta4gradle_1.3.0-beta3gradle_1.3.0-beta2gradle_1.3.0-beta1studio-master-releasestudio-1.4-releasestudio-1.3-releasemastermain
The current example leaks the DoSomethingSlow goroutine for an
arbitrarily long time. In a real server, that can lead to an
out-of-memory failure during events such as network outages; a
more careful version of that example would be too long for a
simple package doc.
Fortunately, there are other short, common patterns using Done
that don't leak and don't require a lot of explanation. Let's
use one of those instead.
Change-Id: I0ad0c6121d06b757a397e0e71be9e01ccfd75f77
Reviewed-on: https://go-review.googlesource.com/4490
Reviewed-by: Andrew Gerrand <adg@golang.org>
-rw-r--r-- | context/context.go | 27 |
1 files changed, 15 insertions, 12 deletions
diff --git a/context/context.go b/context/context.go index 60531fb..b3bc8bb 100644 --- a/context/context.go +++ b/context/context.go @@ -64,18 +64,21 @@ type Context interface { // // Done is provided for use in select statements: // - // // CancelableOperation calls UncancelableOperation and returns as soon as - // // it returns or ctx.Done is closed. - // func CancelableOperation(ctx context.Context) (Result, error) { - // c := make(chan Result, 1) - // go func() { c <- UncancelableOperation() }() - // select { - // case res := <-c: - // return res, nil - // case <-ctx.Done(): - // return nil, ctx.Err() - // } - // } + // // Stream generates values with DoSomething and sends them to out + // // until DoSomething returns an error or ctx.Done is closed. + // func Stream(ctx context.Context, out <-chan Value) error { + // for { + // v, err := DoSomething(ctx) + // if err != nil { + // return err + // } + // select { + // case <-ctx.Done(): + // return ctx.Err() + // case out <- v: + // } + // } + // } // // See http://blog.golang.org/pipelines for more examples of how to use // a Done channel for cancelation. |