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

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

在 golang 中使用 context 包需要澄清

在 golang 中使用 context 包需要澄清

Go
MMTTMM 2022-11-08 14:35:06
我正在學習 Go 語言。我了解取消上下文會在取消父操作或相關操作后中止操作。這應該節省正在進行的操作的資源,其結果將不會被使用?,F在考慮下面的簡單代碼: package main  import (    "context"    "fmt"    "time" )  func main() {    var result int    ctx := context.Background()    ctx, cancel := context.WithCancel(ctx)    ch1 := make(chan int)     go func() {        time.Sleep(time.Second * 5)        //...do some processing        //Send result on the channel or cancel if error        //Lets send result...        ch1 <- 11    }()     go func() {        time.Sleep(time.Second * 2)        //...do some processing        //Send result on the channel or cancel if error        //Lets cancel...        cancel()    }()     select {    case result = <-ch1:        fmt.Println("Processing completed", result)    case <-ctx.Done():        fmt.Println("ctx Cancelled")    }     //Some other processing...    }ctx.Done() 滿足 select 語句。我的問題是,即使在調用取消之后,第一個 goroutine 仍將繼續,因為程序繼續進行“其他處理......”因此,使用上下文的基本目的沒有得到滿足。我認為我的理解中遺漏了一些東西,或者有沒有辦法中止 goroutine,其結果在上下文被取消后將沒有任何用處。請說清楚。
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻1828條經驗 獲得超13個贊

關鍵是你應該通知第一個 goroutine 某事發生了,它需要退出當前的例程。這就是selectgolang 提供的 io-multiplexing 所做的。第一個 goroutine 應該是這樣的


 go func() {

        select {

        case <-time.After(time.Second * 5):

            //...do some processing

            //Send result on the channel or cancel if error

            //Lets send result...

            ch1 <- 11

        case <-ctx.Done():

            fmt.Println("ctx Cancelled again.")

            return

        }

    }()


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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