亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

上下文 ctx.完成未執行,即使上下文已傳遞給 golang 中的函數

上下文 ctx.完成未執行,即使上下文已傳遞給 golang 中的函數

Go
慕村225694 2022-08-30 22:01:04
我只是不明白為什么是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())}
查看完整描述

1 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

goroutine 執行默認分支兩次,并在發送到 時阻止。不執行該案例,因為 goroutine 卡在默認分支中。c<-ctx.Done()


通過從選擇事例而不是分支語句發送來解決此問題。


func A(ctx context.Context) {

    for {

        select {

        case <-ctx.Done():

            fmt.Println("killing AAAA")

            return // kill A at least

        case c <- "yesss":

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

        }

    }

}

您可能看不到單獨具有此更改的,因為程序可以在 goroutine 運行完成之前退出。killing AAAA


等待 goroutine 完成以查看消息:


var wg sync.WaitGroup


func A(ctx context.Context) {

    defer wg.Done()

    for {

        select {

        case <-ctx.Done():

            fmt.Println("killing AAAA")

            return // kill A at least

        case c <- "yesss":

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

        }

    }

}


...


wg.Add(1)

go A(ctx)

time.Sleep(2 * time.Second)

valueReceived := <-c

cancel()

wg.Wait()


查看完整回答
反對 回復 2022-08-30
  • 1 回答
  • 0 關注
  • 111 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號