go context.WithCancel

func func3() {
    gen := func(ctx context.Context) <-chan int {
        dst := make(chan int)
        go func() {
            defer func() {
                fmt.Println("exit inside")
            }()
            var n int
            for {
                select {
                case <-ctx.Done(): // 
                    fmt.Println("exit inside gorotine")
                    return
                case dst <- n:
                    n++
                }
            }
        }()
        return dst
    }
    ctx, cancelFunc := context.WithCancel(context.Background())
    defer cancelFunc()

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

}

官方例子

https://pkg.go.dev/context#WithCancel


关键点 就是ctx 要传进去 goroutine里面, 然后接收到 ctx timeout/cancel信号,要主动退出

评论