golang ctx取消未按预期工作
输出:-golang ctx取消未按预期工作,go,go-context,Go,Go Context,输出:- 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
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())
}
正如在上面的输出中所注意到的,在调用上下文的cancel函数后,numof goroutines仍然是相同的。在cancel函数调用之后,您甚至可以看到goroutine的打印。
我的期望是调用cancel函数将终止该ctx传递到的go例程。Plz帮助我理解上下文的取消功能的行为。上下文取消只是关闭一个频道。您的goroutines应该检查上下文是否已取消,然后返回
./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
go-func(ctx-context.context,i-int){
为了{
挑选{
案例上下文和goroutine是不相关的概念,取消第一个对goroutine没有任何魔力。谢谢。很抱歉这个天真的问题。我对golang是新手,正在尝试学习它。
go func(ctx context.Context, i int) {
for {
select {
case <-ctx.Done():
return
default:
}
fmt.Println("go routine#", i)
}
}(ctx, i)