goroutine 上下文用法

// 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在一个单独的goroutine中生成整数并将它们发送到返回的通道。

//gen的调用方需要在使用生成的整数后取消上下文,以避免泄漏gen启动的内部goroutine。
`package main

import (
"context"
"fmt"
)
func main() {
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
}()
return dst
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel() // cancel when we are finished consuming integers

for n := range gen(ctx) {
	fmt.Println(n)
	if n == 5 {
		break
	}
}

}`

输出结果:
1
2
3
4
5

posted @ 2020-08-26 10:48  刘大侠GG_B  阅读(128)  评论(0编辑  收藏  举报