我试图理解一个简单的Golang例程代码:
package main
import (
"fmt"
"time"
)
func sleep(seconds int, endSignal chan<- bool) {
time.Sleep(time.Duration(seconds) * time.Second)
endSignal <- true
}
func main() {
endSignal := make(chan bool, 1)
go sleep(3, endSignal)
var end bool
for !end {
select {
case end = <-endSignal:
fmt.Println("The end!")
case <-time.After(5 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
end = true
}
}
}
那没关系,但为什么我不能在这个&#34;选择&#34;中使用简单的默认值。块?像这样:
for !end {
select {
case end = <-endSignal:
fmt.Println("The end.")
case <-time.After(4 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
end = true
default:
fmt.Println("No end signal received.")
}
}
获得此输出:
❯ go run goroutines-timeout.go
No end signal received!
No end signal received!
No end signal received!
No end signal received!
...
The end!
我无法理解为什么。
答案 0 :(得分:12)
每次执行time.After(4 * time.Second)
时,都会创建一个新的计时器频道。 select
语句无法记住它在上一次迭代中选择的频道。您还采用了异步操作并将其转换为忙碌循环,从而违背了select
语句的目的。
您需要的只是一个简单的选择,围绕您感兴趣的两个频道。它根本不需要循环。
select {
case <-endSignal:
fmt.Println("The end!")
case <-time.After(4 * time.Second):
fmt.Println("There's no more time to this. Exiting!")
}
https://play.golang.org/p/jb4EE8e6cw
如果你真的想要多次轮询,那么让定时器在for循环之外,这样每次迭代都会检查同一个
timeout := time.After(5 * time.Second)
pollInt := time.Second
for {
select {
case <-endSignal:
fmt.Println("The end!")
return
case <-timeout:
fmt.Println("There's no more time to this. Exiting!")
return
default:
fmt.Println("still waiting")
}
time.Sleep(pollInt)
}