首页 > 解决方案 > 功能中无法解释的等待时间在时间​​包之后(嗯,包时间在时间​​包内)

问题描述

学习时间。在golang之后,我从例子中看到了下面

import (
    "fmt"
    "time"
)

var c chan int

func handle(int) {}

func main() {
    select {
    case m := <-c:
        handle(m)
    case <-time.After(10 * time.Second):
        fmt.Println("timed out")
    }
}

于是深挖源码,(我明白它的作用,但想从源码中看),我去 sleep.go,看看

func After(d Duration) <-chan Time {

    return NewTimer(d).C

}

和新定时器

func NewTimer(d Duration) *Timer {
    c := make(chan Time, 1)
    t := &Timer{
        C: c,
        r: runtimeTimer{
            when: when(d),
            f:    sendTime,
            arg:  c,
        },
    }
    startTimer(&t.r)
    return t

}

这不会导致任何事情。startTimer 只是采用结构的函数

func startTimer(*runtimeTimer)

我真的很想看看是什么让函数在等待 x Duration 之后返回。有人可以帮我解释一下吗?

标签: gotimetimer

解决方案


如果您需要了解更多信息,只需打开GOROOT/src/runtime/time.go 文件并查看startTimer(t *timer)第 208 行的函数(我的 go 版本是 go1.15.6 darwin/amd64)。当你用 IDE 打开 Go 运行时包时,你可以去 head。


推荐阅读