sleep底层实现原理

答案1

进入Go语言中(当前为1.17版本)的sleep.go文件查看源码

sleep的定义如下

  1. // Sleep pauses the current goroutine for at least the duration d.
  2. // A negative or zero duration causes Sleep to return immediately.
  3. func Sleep(d Duration)
  4. // 翻译之后
  5. // Sleep将暂停当前goroutine至少一段时间。
  6. // 负持续时间或零持续时间会导致睡眠立即恢复。
  7. func Sleep(d Duration)

Duration 的定义如下

  1. type Duration int64
  2. const (
  3. minDuration Duration = -1 << 63
  4. maxDuration Duration = 1<<63 - 1
  5. )

Go语言中的time.Sleep实现过程如下

在执行time.Sleep()时,程序会自动使用NewTimer方法创建一个新的Timer,在初始化的过程中我们会u传入当前Goroutine应该被唤醒的时间以及唤醒时需要调用的函数goroutineReady,随后会调用goparkunlock将当前Goroutine陷入休眠状态,当定时器到期时也会调用goroutineReady方法唤醒当前的Goroutine

Timer的结构和NewTimer方法源码如下

  1. type Timer struct {
  2. C <-chan Time
  3. r runtimeTimer
  4. }
  5. func NewTimer(d Duration) *Timer {
  6. c := make(chan Time, 1)
  7. t := &Timer{
  8. C: c,
  9. r: runtimeTimer{
  10. when: when(d),
  11. f: sendTime,
  12. arg: c,
  13. },
  14. }
  15. startTimer(&t.r)
  16. return t
  17. }

参考链接