我试图在Go中隐藏频道。有一个简单的代码
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
i := 0
for {
select {
case <-time.After(3 * time.Second):
fmt.Println("EXIT: 3 seconds")
return
case <-time.After(1 * time.Second):
fmt.Println(i, "second")
}
i++
}
}()
wg.Wait()
}
我希望像这样的控制台结果
0 second
1 second
2 second
EXIT: 3 seconds
但实际上它就像这样
0 second
1 second
2 second
3 second
4 second
5 second
6 second
...
这个计时器我错过了什么?如何解决问题?
答案 0 :(得分:3)
这是因为for循环。评估case <-time.After(3 * time.Second):
语句中select
的每个循环RightHandSide,并为您提供新的计时器。例如,事情应该这样做
stop := time.After(3 * time.Second)
for {
select {
case <-stop:
fmt.Println("EXIT: 3 seconds")
return
case <-time.After(1 * time.Second):
fmt.Println(i, "second")
}
}