【发布时间】:2021-07-12 08:17:57
【问题描述】:
func main() {
fmt.Println("Hello, playground")
ctx, cancel := context.WithCancel(context.Background())
func(ctx context.Context) {
for _, i := range []int{1, 2, 3, 4, 5} {
go func(ctx context.Context, i int) {
for {
fmt.Println("go routine#", i)
}
}(ctx, i)
}
}(ctx)
fmt.Println("before cancel num goroutines", runtime.NumGoroutine())
time.Sleep(1 * time.Millisecond)
cancel()
fmt.Println("after cancel num goroutines", runtime.NumGoroutine())
}
输出:-
./ctxCancel
Hello, playground
before cancel num goroutines 6
go routine# 5
go routine# 5
...
after cancel num goroutines 6
go routine# 1
go routine# 1
go routine# 1
go routine# 1
go routine# 2
正如在上面的输出中注意到的,我看到调用上下文的取消函数后 numof goroutines 仍然相同。您甚至可以在取消函数调用后看到 goroutine 的打印。 我的期望是调用取消函数会终止传递这个 ctx 的 go 例程。请帮我理解上下文取消函数的行为。
【问题讨论】:
-
上下文和 goroutine 是不相关的概念,取消第一个对 goroutine 没有任何作用。
标签: go go-context