上下文 ctx.完成未执行,即使上下文已传递给 golang 中的函数

我只是不明白为什么是ctx。Done() 没有被执行,即使我正在传递上下文并从主调用取消?我在这里做错了什么?


var c = make(chan string)


func A(ctx context.Context) {

 for {

    select {

    case <-ctx.Done():

        fmt.Println("killing AAAA")

        return // kill A at least

    default:

        fmt.Println("in A1.. .. again")

        c <- "yesss"

    }

 }

}


//func B(ctx context.Context) {


func main() {

    ctx, cancel := context.WithCancel(context.Background())

    fmt.Println("BEFORE Number of active goroutines ", runtime.NumGoroutine())

    go A(ctx)

    time.Sleep(2 * time.Second)

    valueReceived := <-c

    cancel()

    fmt.Println("AFTER Number of active goroutines ", runtime.NumGoroutine())

}


慕村225694
浏览 86回答 1
1回答

至尊宝的传说

goroutine 执行默认分支两次,并在发送到 时阻止。不执行该案例,因为 goroutine 卡在默认分支中。c<-ctx.Done()通过从选择事例而不是分支语句发送来解决此问题。func A(ctx context.Context) {&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("killing AAAA")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return // kill A at least&nbsp; &nbsp; &nbsp; &nbsp; case c <- "yesss":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("in A1.. .. again")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}您可能看不到单独具有此更改的,因为程序可以在 goroutine 运行完成之前退出。killing AAAA等待 goroutine 完成以查看消息:var wg sync.WaitGroupfunc A(ctx context.Context) {&nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-ctx.Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("killing AAAA")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return // kill A at least&nbsp; &nbsp; &nbsp; &nbsp; case c <- "yesss":&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("in A1.. .. again")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}...wg.Add(1)go A(ctx)time.Sleep(2 * time.Second)valueReceived := <-ccancel()wg.Wait()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go