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 例程。请帮助我了解上下文取消功能的行为。