go - 功能中无法解释的等待时间在时间包之后(嗯,包时间在时间包内)
问题描述
学习时间。在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 之后返回。有人可以帮我解释一下吗?
解决方案
如果您需要了解更多信息,只需打开GOROOT/src/runtime/time.go
文件并查看startTimer(t *timer)
第 208 行的函数(我的 go 版本是 go1.15.6 darwin/amd64)。当你用 IDE 打开 Go 运行时包时,你可以去 head。
推荐阅读
- c# - 应用 TextWrapping 后如何获得具有内联元素支持的 TextBlock 行?
- spring-boot - 使用代理进行 Springboot 协议测试
- javascript - 按钮 2 显示与按钮 1 显示相同的文本
- php - 如何将页面分配给子页面
- css - 如何在标题中添加图像而不是图标反应原生元素
- c++ - C ++从2个不同的向量中删除shared_ptr
- android - Android openGL ES 3 Vector3f 和 Matrix4f 类的替代品是什么?
- swift - 当我滚动 SwiftUI/Swift 时,图像在列表中消失
- regex - 如何匹配 $ 或 $$ 但如果它们是这些 <$ 和 <$$ 中的任何一个则不匹配
- mysql - 错误:语句需要的资源多于资源队列允许的资源