【发布时间】:2014-07-19 19:27:15
【问题描述】:
以下代码来自go by example - timers
package main
import (
"time"
"fmt"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
timer1 := time.NewTimer(time.Second * 1)
<-timer1.C
fmt.Println("Timer 1 expired")
timer2 := time.NewTimer(300) //change the duration to be more shorter
go func() {
<-timer2.C
fmt.Printf("Timer 2 expired")
}()
stop2 := timer2.Stop()
if stop2 {
fmt.Printf("Timer 2 stopped")
}
}
如果我运行上面的代码,输出将是这样的(结果一):
Timer 1 expired
Timer 2 stopped
但如果我将匿名函数的主体更改为:
fmt.Printf("Timer 2 expired")
<-timer2.C
输出还是和以前一样。我很困惑,为什么第二个输出不像(结果二):
Timer 1 expired
Timer 2 expired
Timer 2 stopped
根据我的理解 会阻塞 goroutine 的剩余部分,直到计时器通道得到一个值,所以如果我把 fmt.Printf("Timer 2 expired") 之后的输出会像结果一,但如果我把 fmt.Printf("Timer 2 expired") 放在 ,我认为打印动作不会被阻塞。
希望有人能帮帮我,谢谢大家。
【问题讨论】:
标签: timer go blocking goroutine