1 回答

TA貢獻1817條經驗 獲得超14個贊
問題是你的wg.Done()位置不對。它必須在你的 goroutine 中,但是你在 goroutine 啟動之前執(zhí)行它,所以你的程序很可能在做任何工作之前退出。
改變這個:
defer wg.Done()
go func() {
對此:
go func() {
defer wg.Done()
當然,你將擁有一個無限運行的 goroutine,因為你的for循環(huán)沒有退出條件。您需要添加一個,可能是通過檢查通道關閉來添加:
select {
case x, ok := <-c:
if !ok { // channel was closed
return
}
fmt.Println("Read", x)
case t :=<-ti:
fmt.Println("TIMED OUT with "+t.String())
}
然后告訴你的主 go 例程在完成后關閉通道:
c <- 40
c <- 50
close(c) // We're done, so tell the goroutine to finish up
wg.Wait() // But wait until it's done
- 1 回答
- 0 關注
- 117 瀏覽
添加回答
舉報