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()
- 1 回答
- 0 關注
- 111 瀏覽
添加回答
舉報