我正在學(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
}
}()
- 1 回答
- 0 關(guān)注
- 144 瀏覽
添加回答
舉報(bào)
0/150
提交
取消