第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

在 golang 中使用 context 包需要澄清

在 golang 中使用 context 包需要澄清

Go
MMTTMM 2022-11-08 14:35:06
我正在學(xué)習(xí) Go 語言。我了解取消上下文會(huì)在取消父操作或相關(guān)操作后中止操作。這應(yīng)該節(jié)省正在進(jìn)行的操作的資源,其結(jié)果將不會(huì)被使用?,F(xiàn)在考慮下面的簡單代碼: 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 語句。我的問題是,即使在調(diào)用取消之后,第一個(gè) goroutine 仍將繼續(xù),因?yàn)槌绦蚶^續(xù)進(jìn)行“其他處理......”因此,使用上下文的基本目的沒有得到滿足。我認(rèn)為我的理解中遺漏了一些東西,或者有沒有辦法中止 goroutine,其結(jié)果在上下文被取消后將沒有任何用處。請說清楚。
查看完整描述

1 回答

?
慕田峪7331174

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超13個(gè)贊

關(guān)鍵是你應(yīng)該通知第一個(gè) goroutine 某事發(fā)生了,它需要退出當(dāng)前的例程。這就是selectgolang 提供的 io-multiplexing 所做的。第一個(gè) goroutine 應(yīng)該是這樣的


 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

        }

    }()


查看完整回答
反對 回復(fù) 2022-11-08
  • 1 回答
  • 0 關(guān)注
  • 144 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)