登录
首页 >  Golang >  Go问答

golang ctx 取消机制失效

来源:stackoverflow

时间:2024-02-15 19:51:19 414浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《golang ctx 取消机制失效》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

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 goroutine 仍然相同。您甚至可以在取消函数调用后看到 goroutine 的打印结果。 我的期望是调用 cancel 函数将终止传递此 ctx 的 go 例程。请帮助我理解上下文取消函数的行为。


正确答案


上下文取消只是关闭一个通道。你的 goroutine 应该检查上下文是否被取消,然后返回。

go func(ctx context.Context, i int) {
                for {
                    select {
                        case <-ctx.Done():
                           return
                        default:
                     }
                    fmt.Println("go routine#", i)
                }

            }(ctx, i)

取消后,您应该等待 goroutine 终止。他们不会立即全部收到取消通知。

本篇关于《golang ctx 取消机制失效》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>