Below code is from 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")
}
}
If I run above code, the output will be like(result one):
Timer 1 expired
Timer 2 stopped
but if I change the body of the anonymous func to be:
fmt.Printf("Timer 2 expired")
<-timer2.C
the output is still like before. I'm confused, why the second output is not like(result two):
Timer 1 expired
Timer 2 expired
Timer 2 stopped
As per my understanding <-timer2.C blocks the remain of goroutine until the timer channel get a value, so if I put fmt.Printf("Timer 2 expired") after <-timer2.C the output will like result one, but if I put fmt.Printf("Timer 2 expired") before <-timer2.C, I think the print action will not be blocked.
Hope someone could give me a hand, thank you all.