Commit 31f50643 authored by Jaana Burcu Dogan's avatar Jaana Burcu Dogan

context: add comments to the WithCancel example, apply minor improvements

Fixes #17534.

Change-Id: I28af74b287a5a09d5f6607a012f3d5d133b04ed2
Reviewed-on: https://go-review.googlesource.com/32017Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
parent 117c9c35
...@@ -10,31 +10,38 @@ import ( ...@@ -10,31 +10,38 @@ import (
"time" "time"
) )
// This example demonstrate the use of a cancelable context preventing a // This example demonstrates the use of a cancelable context to prevent a
// goroutine leak. By the end of the example func's execution, the "count" // goroutine leak. By the end of the example function, the goroutine started
// goroutine is canceled. // by gen will return without leaking.
func ExampleWithCancel() { func ExampleWithCancel() {
count := func(ctx context.Context, dst chan<- int) { // gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1 n := 1
for { go func() {
select { for {
case dst <- n: select {
n++ case <-ctx.Done():
case <-ctx.Done(): return // returning not to leak the goroutine
return case dst <- n:
n++
}
} }
} }()
return dst
} }
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel() // cancel when we are finished consuming integers
ints := make(chan int) for n := range gen(ctx) {
go count(ctx, ints)
for n := range ints {
fmt.Println(n) fmt.Println(n)
if n == 5 { if n == 5 {
return break
} }
} }
// Output: // Output:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment