我正在學習 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
}
}()
- 1 回答
- 0 關注
- 154 瀏覽
添加回答
舉報
0/150
提交
取消