go语言--time.After()

go语言--time.After()

https://blog.csdn.net/cyk2396/article/details/78873396

1.源码分析:

// After waits for the duration to elapse and then sends the current time
// on the returned channel.
// It is equivalent to NewTimer(d).C.
// The underlying Timer is not recovered by the garbage collector
// until the timer fires. If efficiency is a concern, use NewTimer
// instead and call Timer.Stop if the timer is no longer needed.
func After(d Duration) <-chan Time {
return NewTimer(d).C
}

根据注释可知,在等待给定的一段时间后,向返回值发送当前时间,返回值是一个单向只读通道

2.demo:

func main() {
    c := make(chan int, 1)
    select {
    case m := <-c:
        fmt.Println(m)
    case d := <-time.After(5 * time.Second):
        fmt.Println("time out")
        fmt.Println("current Time :", d)
    }
 
}

time out
current Time : 2017-12-22 15:04:05.0462009 +0800 CST m=+5.004000001
3.分析:

第一个case中,通道c一直处于阻塞状态;第二个case中,在time.After()结束后,从返回值通道中取出一个值赋予了d,该值就是当前时间

猜你喜欢

转载自www.cnblogs.com/Leo_wl/p/9268964.html