这是一段代码,它输出推送到通道的整数列表。否则,选择检查并打印必要的超时消息。
package main
import (
"fmt"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
wg.Add(1)
c := make(chan int)
go readFromChannel(c, time.After(time.Duration(2)*time.Second))
// time.Sleep(time.Duration(5) * time.Second) //Talking about uncommenting this line
c <- 10
c <- 20
c <- 30
c <- 40
c <- 50
wg.Wait()
}
func readFromChannel(c chan int, ti <-chan time.Time) {
defer wg.Done()
go func() {
for {
select {
case x := <-c:
fmt.Println("Read", x)
case t :=<-ti:
fmt.Println("TIMED OUT with "+t.String())
}
}
}()
}
另外,这里还有相同的游乐场链接: https: //play.golang.org/p/4hNWze4Pfwr 此代码输出整数列表,例如
Read 10
Read 20
Read 30
Read 40
Read 50
但是,当我取消注释使主例程进入睡眠状态 5 秒的行(在代码中称为注释/行号 16)时,输出更改为:
TIMED OUT with 2009-11-10 23:00:02 +0000 UTC m=+2.000000001
Read 10
Read 20
Read 30
Read 40
我想了解为什么Read 50在第二种情况下没有打印最后一个。
大话西游666
相关分类