Timer-一次性定时器,Ticker-周期性定时器。从1.23版本开始,将异步实现改为同步实现,但你仍然可以使用AfterFunc创建异步定时器,或者通过改变asynctimerchan变量启用异步实现
asynctimerchan变量可选项如下
asynctimerchan
description
0
同步实现,从1.23版本开始启用
1
旧版异步实现
2
同1,异步实现,但修复了1的问题,debug用
定时器的精确度因系统不同而不同,具体如下
OS
resolution
Unix
~1ms
>= Windows 1803
~0.5ms
< Windows 1803
~16ms
快速上手 深入了解源代码前,先了解其功能如何使用
Timer-一次性定时器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package mainimport ( "fmt" "time" ) func main () { timer1 := time.NewTimer(2 * time.Second) <-timer1.C fmt.Println("Timer 1 fired" ) timer2 := time.NewTimer(time.Second) go func () { <-timer2.C fmt.Println("Timer 2 fired" ) }() stop2 := timer2.Stop() if stop2 { fmt.Println("Timer 2 stopped" ) } time.Sleep(2 * time.Second) }
上述示例代码运行效果如下
Ticker-周期性定时器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 package mainimport ( "fmt" "time" ) func main () { ticker := time.NewTicker(500 * time.Millisecond) done := make (chan bool ) go func () { for { select { case <-done: return case t := <-ticker.C: fmt.Println("Tick at" , t) } } }() time.Sleep(1600 * time.Millisecond) ticker.Stop() done <- true fmt.Println("Ticker stopped" ) }
上述示例代码运行效果如下
数据结构 time.Timer以及time.Ticker数据结构同源,在实际运行时都会转换成runtime的timeTimer,数据结构的字段释义如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 type Timer struct { C <-chan Time initTimer bool } type Ticker struct { C <-chan Time initTicker bool } type timeTimer struct { c unsafe.Pointer init bool timer } type timer struct { mu mutex astate atomic.Uint8 state uint8 isChan bool isFake bool blocked uint32 when int64 period int64 f func (arg any, seq uintptr , delay int64 ) arg any seq uintptr ts *timers sendLock mutex isSending atomic.Int32 } type timers struct { mu mutex heap []timerWhen len atomic.Uint32 zombies atomic.Int32 raceCtx uintptr minWhenHeap atomic.Int64 minWhenModified atomic.Int64 syncGroup *synctestGroup } type timerWhen struct { timer *timer when int64 }
timer的state状态总共占用3个位,如下所示
state_name
state_value
description
timerHeaped
1
定时器已经放在某个P的timers最小堆中
timerModified
2
t.when被修改但还没更新heap[i].when,如果定时器不在heap,忽略
timerZombie
4
定时器被停止,但还放在heap里,可以跟timerModified位共存。定时器为zombie时可以发送数据到channel,因为数据不会被读取
注意:
timerModified和timerZombie的前提都是timerHeaped
无法直接把timer移除出timers.heap,因为别的P可能已经拿到了这个timer
timer有这几个状态位意味着最小堆还没有重新调整,timer还放在之前的位置上(不满足最小堆)
创建定时器 NewTimer & NewTicker 创建/获取定时器,过期时刻为当前时刻加目标时长
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 func NewTimer (d Duration) *Timer { c := make (chan Time, 1 ) t := (*Timer)(newTimer(when(d), 0 , sendTime, c, syncTimer(c))) t.C = c return t } func NewTicker (d Duration) *Ticker { if d <= 0 { panic ("non-positive interval for NewTicker" ) } c := make (chan Time, 1 ) t := (*Ticker)(unsafe.Pointer(newTimer(when(d), int64 (d), sendTime, c, syncTimer(c)))) t.C = c return t } func newTimer (when, period int64 , f func (arg any, seq uintptr , delay int64 ) , arg any, c *hchan) *timeTimer { t := new (timeTimer) t.timer.init(nil , nil ) t.trace("new" ) if c != nil { lockInit(&t.sendLock, lockRankTimerSend) t.isChan = true c.timer = &t.timer if c.dataqsiz == 0 { throw("invalid timer channel: no capacity" ) } } if gr := getg().syncGroup; gr != nil { t.isFake = true } t.modify(when, period, f, arg, 0 ) t.init = true return t }
为了避免代码过长影响阅读,其他依赖方法列在下方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 func when (d Duration) int64 { if d <= 0 { return runtimeNano() } t := runtimeNano() + int64 (d) if t < 0 { t = 1 <<63 - 1 } return t } func sendTime (c any, seq uintptr , delta int64 ) { select { case c.(chan Time) <- Now().Add(Duration(-delta)): default : } } func syncTimer (c chan Time) unsafe.Pointer { if asynctimerchan.Value() == "1" { asynctimerchan.IncNonDefault() return nil } return *(*unsafe.Pointer)(unsafe.Pointer(&c)) } func (t *timer) init(f func (arg any, seq uintptr , delay int64 ) , arg any) { lockInit(&t.mu, lockRankTimer) t.f = f t.arg = arg } func (t *timer) modify(when, period int64 , f func (arg any, seq uintptr , delay int64 ) , arg any, seq uintptr ) bool { if when <= 0 { throw("timer when must be positive" ) } if period < 0 { throw("timer period must be non-negative" ) } async := debug.asynctimerchan.Load() != 0 if !async && t.isChan { lock(&t.sendLock) } t.lock() if async { t.maybeRunAsync() } t.trace("modify" ) oldPeriod := t.period t.period = period if f != nil { t.f = f t.arg = arg t.seq = seq } wake := false pending := t.when > 0 t.when = when if t.state&timerHeaped != 0 { t.state |= timerModified if t.state&timerZombie != 0 { t.ts.zombies.Add(-1 ) t.state &^= timerZombie } if min := t.ts.minWhenModified.Load(); min == 0 || when < min { wake = true t.astate.Store(t.state) t.ts.updateMinWhenModified(when) } } add := t.needsAdd() if !async && t.isChan { t.seq++ if oldPeriod == 0 && t.isSending.Load() > 0 { pending = true } } t.unlock() if !async && t.isChan { if timerchandrain(t.hchan()) { pending = true } unlock(&t.sendLock) } if add { t.maybeAdd() } if wake { wakeNetPoller(when) } return pending } func (t *timer) maybeRunAsync() { assertLockHeld(&t.mu) if t.state&timerHeaped == 0 && t.isChan && t.when > 0 { if now := nanotime(); t.when <= now { systemstack(func () { t.unlockAndRun(now) }) t.lock() } } } func (t *timer) unlockAndRun(now int64 ) { t.trace("unlockAndRun" ) assertLockHeld(&t.mu) if t.ts != nil { assertLockHeld(&t.ts.mu) } if t.state&(timerModified|timerZombie) != 0 { badTimer() } f := t.f arg := t.arg seq := t.seq var next int64 delay := now - t.when if t.period > 0 { next = t.when + t.period*(1 +delay/t.period) if next < 0 { next = maxWhen } } else { next = 0 } ts := t.ts t.when = next if t.state&timerHeaped != 0 { t.state |= timerModified if next == 0 { t.state |= timerZombie t.ts.zombies.Add(1 ) } t.updateHeap() } async := debug.asynctimerchan.Load() != 0 if !async && t.isChan && t.period == 0 { if t.isSending.Add(1 ) < 0 { throw("too many concurrent timer firings" ) } } t.unlock() if ts != nil { ts.unlock() } if ts != nil && ts.syncGroup != nil { gp := getg() if gp.syncGroup != nil { throw("unexpected syncgroup set" ) } gp.syncGroup = ts.syncGroup ts.syncGroup.changegstatus(gp, _Gdead, _Grunning) } if !async && t.isChan { lock(&t.sendLock) if t.period == 0 { if t.isSending.Add(-1 ) < 0 { throw("mismatched isSending updates" ) } } if t.seq != seq { f = func (any, uintptr , int64 ) {} } } f(arg, seq, delay) if !async && t.isChan { unlock(&t.sendLock) } if ts != nil && ts.syncGroup != nil { gp := getg() ts.syncGroup.changegstatus(gp, _Grunning, _Gdead) gp.syncGroup = nil } if ts != nil { ts.lock() } } func (ts *timers) updateMinWhenModified(when int64 ) { for { old := ts.minWhenModified.Load() if old != 0 && old < when { return } if ts.minWhenModified.CompareAndSwap(old, when) { return } } } func (t *timer) needsAdd() bool { assertLockHeld(&t.mu) need := t.state&timerHeaped == 0 && t.when > 0 && (!t.isChan || t.isFake || t.blocked > 0 ) if need { t.trace("needsAdd+" ) } else { t.trace("needsAdd-" ) } return need } func timerchandrain (c *hchan) bool { if atomic.Loaduint(&c.qcount) == 0 { return false } lock(&c.lock) any := false for c.qcount > 0 { any = true typedmemclr(c.elemtype, chanbuf(c, c.recvx)) c.recvx++ if c.recvx == c.dataqsiz { c.recvx = 0 } c.qcount-- } unlock(&c.lock) return any } func (t *timer) maybeAdd() { mp := acquirem() var ts *timers if t.isFake { sg := getg().syncGroup if sg == nil { throw("invalid timer: fake time but no syncgroup" ) } ts = &sg.timers } else { ts = &mp.p.ptr().timers } ts.lock() ts.cleanHead() t.lock() t.trace("maybeAdd" ) when := int64 (0 ) wake := false if t.needsAdd() { t.state |= timerHeaped when = t.when wakeTime := ts.wakeTime() wake = wakeTime == 0 || when < wakeTime ts.addHeap(t) } t.unlock() ts.unlock() releasem(mp) if wake { wakeNetPoller(when) } } func (ts *timers) cleanHead() { ts.trace("cleanHead" ) assertLockHeld(&ts.mu) gp := getg() for { if len (ts.heap) == 0 { return } if gp.preemptStop { return } n := len (ts.heap) if t := ts.heap[n-1 ].timer; t.astate.Load()&timerZombie != 0 { t.lock() if t.state&timerZombie != 0 { t.state &^= timerHeaped | timerZombie | timerModified t.ts = nil ts.zombies.Add(-1 ) ts.heap[n-1 ] = timerWhen{} ts.heap = ts.heap[:n-1 ] } t.unlock() continue } t := ts.heap[0 ].timer if t.ts != ts { throw("bad ts" ) } if t.astate.Load()&(timerModified|timerZombie) == 0 { return } t.lock() updated := t.updateHeap() t.unlock() if !updated { return } } } func (ts *timers) updateMinWhenHeap() { assertWorldStoppedOrLockHeld(&ts.mu) if len (ts.heap) == 0 { ts.minWhenHeap.Store(0 ) } else { ts.minWhenHeap.Store(ts.heap[0 ].when) } } func (ts *timers) wakeTime() int64 { nextWhen := ts.minWhenModified.Load() when := ts.minWhenHeap.Load() if when == 0 || (nextWhen != 0 && nextWhen < when) { when = nextWhen } return when } func wakeNetPoller (when int64 ) { if sched.lastpoll.Load() == 0 { pollerPollUntil := sched.pollUntil.Load() if pollerPollUntil == 0 || pollerPollUntil > when { netpollBreak() } } else { if GOOS != "plan9" { wakep() } } }
AfterFunc 创建/获取一次性定时器,与NewTimer的区别是使用了用户自定义函数,此外,该定时器是异步的
1 2 3 4 5 6 7 8 func AfterFunc (d Duration, f func () ) *Timer { return (*Timer)(newTimer(when(d), 0 , goFunc, f, nil )) } func goFunc (arg any, seq uintptr , delta int64 ) { go arg.(func () )() }
Sleep 创建定时器或重用当前G的定时器,把当前goroutine挂起休眠至少ns纳秒时间
初始化g.timer或重用当前G的timer
计算过期时刻when,纪录到g.sleepWhen
调用modify更新定时器,将当前goroutine挂起等待唤醒
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 func timeSleep (ns int64 ) { if ns <= 0 { return } gp := getg() t := gp.timer if t == nil { t = new (timer) t.init(goroutineReady, gp) if gp.syncGroup != nil { t.isFake = true } gp.timer = t } var now int64 if sg := gp.syncGroup; sg != nil { now = sg.now } else { now = nanotime() } when := now + ns if when < 0 { when = maxWhen } gp.sleepWhen = when if t.isFake { resetForSleep(gp, nil ) gopark(nil , nil , waitReasonSleep, traceBlockSleep, 1 ) } else { gopark(resetForSleep, nil , waitReasonSleep, traceBlockSleep, 1 ) } } func resetForSleep (gp *g, _ unsafe.Pointer) bool { gp.timer.reset(gp.sleepWhen, 0 ) return true }
After & Tick 创建定时器,返回定时器的channel,属于NewTimer/NewTicker函数的封装。go1.22及之前的版本中,如果在for循环使用After会申请大量内存,加剧GC压力
1 2 3 4 5 6 7 8 9 10 11 12 func After (d Duration) <-chan Time { return NewTimer(d).C } func Tick (d Duration) <-chan Time { if d <= 0 { return nil } return NewTicker(d).C }
定时器相关 停止定时器 停止定时器,因为定时器可能被其他P持有,只修改状态。具体逻辑如下
如果是异步定时器,判断定时器是否需要触发执行函数f
定时器字段更新
更新定时器状态state的timerZombie位
重置when
更新版本计数器
将状态state复制到astate上(到这里就解锁了)
如果是同步定时器,清空channel(t.arg)的buf缓冲区
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 func (t *Timer) Stop() bool { if !t.initTimer { panic ("time: Stop called on uninitialized Timer" ) } return stopTimer(t) } func (t *Ticker) Stop() { if !t.initTicker { return } stopTimer((*Timer)(unsafe.Pointer(t))) } func stopTimer (t *timeTimer) bool { if t.isFake && getg().syncGroup == nil { panic ("stop of synctest timer from outside bubble" ) } return t.stop() } func (t *timer) stop() bool { async := debug.asynctimerchan.Load() != 0 if !async && t.isChan { lock(&t.sendLock) } t.lock() t.trace("stop" ) if async { t.maybeRunAsync() } if t.state&timerHeaped != 0 { t.state |= timerModified if t.state&timerZombie == 0 { t.state |= timerZombie t.ts.zombies.Add(1 ) } } pending := t.when > 0 t.when = 0 if !async && t.isChan { t.seq++ if t.period == 0 && t.isSending.Load() > 0 { pending = true } } t.unlock() if !async && t.isChan { unlock(&t.sendLock) if timerchandrain(t.hchan()) { pending = true } } return pending }
重置定时器 重置定时器,本质是modify函数调用,更新timer状态、添加到最小堆、中断网络轮询。需要先调用Stop才能确保安全调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 func (t *Timer) Reset(d Duration) bool { if !t.initTimer { panic ("time: Reset called on uninitialized Timer" ) } w := when(d) return resetTimer(t, w, 0 ) } func (t *Ticker) Reset(d Duration) { if d <= 0 { panic ("non-positive interval for Ticker.Reset" ) } if !t.initTicker { panic ("time: Reset called on uninitialized Ticker" ) } resetTimer((*Timer)(unsafe.Pointer(t)), when(d), int64 (d)) } func resetTimer (t *timeTimer, when, period int64 ) bool { if t.isFake && getg().syncGroup == nil { panic ("reset of synctest timer from outside bubble" ) } return t.reset(when, period) } func (t *timer) reset(when, period int64 ) bool { return t.modify(when, period, nil , nil , 0 ) }
最小堆相关 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 func (t *timer) updateHeap() (updated bool ) { assertWorldStoppedOrLockHeld(&t.mu) t.trace("updateHeap" ) ts := t.ts if ts == nil || t != ts.heap[0 ].timer { badTimer() } assertLockHeld(&ts.mu) if t.state&timerZombie != 0 { t.state &^= timerHeaped | timerZombie | timerModified ts.zombies.Add(-1 ) ts.deleteMin() return true } if t.state&timerModified != 0 { t.state &^= timerModified ts.heap[0 ].when = t.when ts.siftDown(0 ) ts.updateMinWhenHeap() return true } return false } func (ts *timers) initHeap() { if len (ts.heap) <= 1 { return } for i := int (uint (len (ts.heap)-1 -1 ) / timerHeapN); i >= 0 ; i-- { ts.siftDown(i) } } func (ts *timers) addHeap(t *timer) { assertWorldStoppedOrLockHeld(&ts.mu) if netpollInited.Load() == 0 { netpollGenericInit() } if t.ts != nil { throw("ts set in timer" ) } t.ts = ts ts.heap = append (ts.heap, timerWhen{t, t.when}) ts.siftUp(len (ts.heap) - 1 ) if t == ts.heap[0 ].timer { ts.updateMinWhenHeap() } } func (ts *timers) siftUp(i int ) { heap := ts.heap if i >= len (heap) { badTimer() } tw := heap[i] when := tw.when if when <= 0 { badTimer() } for i > 0 { p := int (uint (i-1 ) / timerHeapN) if when >= heap[p].when { break } heap[i] = heap[p] i = p } if heap[i].timer != tw.timer { heap[i] = tw } } func (ts *timers) siftDown(i int ) { heap := ts.heap n := len (heap) if i >= n { badTimer() } if i*timerHeapN+1 >= n { return } tw := heap[i] when := tw.when if when <= 0 { badTimer() } for { leftChild := i*timerHeapN + 1 if leftChild >= n { break } w := when c := -1 for j, tw := range heap[leftChild:min(leftChild+timerHeapN, n)] { if tw.when < w { w = tw.when c = leftChild + j } } if c < 0 { break } heap[i] = heap[c] i = c } if heap[i].timer != tw.timer { heap[i] = tw } } func (ts *timers) deleteMin() { assertLockHeld(&ts.mu) t := ts.heap[0 ].timer if t.ts != ts { throw("wrong timers" ) } t.ts = nil last := len (ts.heap) - 1 if last > 0 { ts.heap[0 ] = ts.heap[last] } ts.heap[last] = timerWhen{} ts.heap = ts.heap[:last] if last > 0 { ts.siftDown(0 ) } ts.updateMinWhenHeap() if last == 0 { ts.minWhenModified.Store(0 ) } }
goroutine调度相关 take 销毁P时,把最小堆里的timer全部迁移走
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 func (ts *timers) take(src *timers) { ts.trace("take" ) assertWorldStopped() if len (src.heap) > 0 { for _, tw := range src.heap { t := tw.timer t.ts = nil if t.state&timerZombie != 0 { t.state &^= timerHeaped | timerZombie | timerModified } else { t.state &^= timerModified ts.addHeap(t) } } src.heap = nil src.zombies.Store(0 ) src.minWhenHeap.Store(0 ) src.minWhenModified.Store(0 ) src.len .Store(0 ) ts.len .Store(uint32 (len (ts.heap))) } }
check 清理最小堆,把所有标记删除的timer都移除出最小堆,如果最小的timer到期,则执行回调函数f运行。调度时,寻找可运行的G时调用(findRunnable或stealWork)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 func (ts *timers) check(now int64 ) (rnow, pollUntil int64 , ran bool ) { ts.trace("check" ) next := ts.wakeTime() if next == 0 { return now, 0 , false } if now == 0 { now = nanotime() } zombies := ts.zombies.Load() if zombies < 0 { badTimer() } force := ts == &getg().m.p.ptr().timers && int (zombies) > int (ts.len .Load())/4 if now < next && !force { return now, next, false } ts.lock() if len (ts.heap) > 0 { ts.adjust(now, false ) for len (ts.heap) > 0 { if tw := ts.run(now); tw != 0 { if tw > 0 { pollUntil = tw } break } ran = true } force = ts == &getg().m.p.ptr().timers && int (ts.zombies.Load()) > int (ts.len .Load())/4 if force { ts.adjust(now, true ) } } ts.unlock() return now, pollUntil, ran }
其他依赖方法列在下方
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 func (ts *timers) adjust(now int64 , force bool ) { ts.trace("adjust" ) assertLockHeld(&ts.mu) if !force { first := ts.minWhenModified.Load() if first == 0 || first > now { if verifyTimers { ts.verify() } return } } ts.minWhenHeap.Store(ts.wakeTime()) ts.minWhenModified.Store(0 ) changed := false for i := 0 ; i < len (ts.heap); i++ { tw := &ts.heap[i] t := tw.timer if t.ts != ts { throw("bad ts" ) } if t.astate.Load()&(timerModified|timerZombie) == 0 { continue } t.lock() switch { case t.state&timerHeaped == 0 : badTimer() case t.state&timerZombie != 0 : ts.zombies.Add(-1 ) t.state &^= timerHeaped | timerZombie | timerModified n := len (ts.heap) ts.heap[i] = ts.heap[n-1 ] ts.heap[n-1 ] = timerWhen{} ts.heap = ts.heap[:n-1 ] t.ts = nil i-- changed = true case t.state&timerModified != 0 : tw.when = t.when t.state &^= timerModified changed = true } t.unlock() } if changed { ts.initHeap() } ts.updateMinWhenHeap() if verifyTimers { ts.verify() } } func (ts *timers) verify() { assertLockHeld(&ts.mu) for i, tw := range ts.heap { if i == 0 { continue } p := int (uint (i-1 ) / timerHeapN) if tw.when < ts.heap[p].when { print ("bad timer heap at " , i, ": " , p, ": " , ts.heap[p].when, ", " , i, ": " , tw.when, "\n" ) throw("bad timer heap" ) } } if n := int (ts.len .Load()); len (ts.heap) != n { println ("timer heap len" , len (ts.heap), "!= atomic len" , n) throw("bad timer heap len" ) } } func (ts *timers) run(now int64 ) int64 { ts.trace("run" ) assertLockHeld(&ts.mu) Redo: if len (ts.heap) == 0 { return -1 } tw := ts.heap[0 ] t := tw.timer if t.ts != ts { throw("bad ts" ) } if t.astate.Load()&(timerModified|timerZombie) == 0 && tw.when > now { return tw.when } t.lock() if t.updateHeap() { t.unlock() goto Redo } if t.state&timerHeaped == 0 || t.state&timerModified != 0 { badTimer() } if t.when > now { t.unlock() return t.when } t.unlockAndRun(now) assertLockHeld(&ts.mu) return 0 }
timeSleepUntil 遍历所有P,找到全局最小的when。由sysmon、checkdead函数调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 func timeSleepUntil () int64 { next := int64 (maxWhen) lock(&allpLock) for _, pp := range allp { if pp == nil { continue } if w := pp.timers.wakeTime(); w != 0 { next = min(next, w) } } unlock(&allpLock) return next }
channel相关 虽说是跟channel相关,实际上,在执行<-t.C
等待超时时,就会使用到下面的方法
maybeRunChan 判断是否需要更新timer状态、执行函数f。具体逻辑如下
不满足条件则返回
timer已经放在最小堆上,那么过期后自动发送到channel
timer从未执行过
timer还未到触发时刻
满足条件则更新timer状态、执行函数f
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 func (t *timer) maybeRunChan() { if t.isFake { t.lock() var timerGroup *synctestGroup if t.ts != nil { timerGroup = t.ts.syncGroup } t.unlock() sg := getg().syncGroup if sg == nil { panic (plainError("synctest timer accessed from outside bubble" )) } if timerGroup != nil && sg != timerGroup { panic (plainError("timer moved between synctest bubbles" )) } return } if t.astate.Load()&timerHeaped != 0 { return } t.lock() now := nanotime() if t.state&timerHeaped != 0 || t.when == 0 || t.when > now { t.trace("maybeRunChan-" ) t.unlock() return } t.trace("maybeRunChan+" ) systemstack(func () { t.unlockAndRun(now) }) }
blockTimerChan & unblockTimerChan 1 2 3 4 5 t := time.NewTimer(10 * time.Millisecond) <-t.C
上述示例代码,如果这个channel是属于一个定时器的,那么在G挂起前、唤醒后,需要修改定时器的state-状态、blocked-标记等。函数详细注释如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 func blockTimerChan (c *hchan) { t := c.timer if t.isFake { return } t.lock() t.trace("blockTimerChan" ) if !t.isChan { badTimer() } t.blocked++ if t.state&timerHeaped != 0 && t.state&timerZombie != 0 && t.when > 0 { t.state &^= timerZombie t.ts.zombies.Add(-1 ) } add := t.needsAdd() t.unlock() if add { t.maybeAdd() } } func unblockTimerChan (c *hchan) { t := c.timer if t.isFake { return } t.lock() t.trace("unblockTimerChan" ) if !t.isChan || t.blocked == 0 { badTimer() } t.blocked-- if t.blocked == 0 && t.state&timerHeaped != 0 && t.state&timerZombie == 0 { t.state |= timerZombie t.ts.zombies.Add(1 ) } t.unlock() }
定时器示例解析
创建定时器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 t := time.NewTimer(2 * time.Second)
当前G挂起等待
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <-t.C
定时器到期通知
GMP调度执行findRunnable或stealWork,发现定时器过期,发送信号给channel,唤醒goroutine,流程如下
当前G唤醒继续执行
当前G唤醒后,调用unblockTimerChan
参考文档 Resetting timers in Go timer 在 Golang 中可以有多精确? 论golang Timer Reset方法使用的正确姿势 #74 time.Timer 源码分析 (Go 1.14) 【 Go 夜读 】