【发布时间】:2017-01-05 20:15:06
【问题描述】:
我正在尝试理解 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
}
}
}
很好,但是为什么我不能在这个“选择”块中使用简单的默认值?像这样的:
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!
我不明白为什么。
【问题讨论】:
-
这就是
default所做的。你能解释一下你预计会发生什么吗? -
我希望
default这样做,而time.After的时间还没有结束。 -
我不明白,这就是它的作用。
time.After的情况不会执行,因为采用了默认情况。 -
如果之前有
time.After的情况,为什么要采取default?