从99.9%CPU浅谈Golang的定时器实现原理
1. 情景描述:
线上某系统大约运行了半个多月的时间,突然发现系统的交易处理时间延迟从最初的70ms 变成7s,也就是系统性能下降了100倍左右。经过一番盘查发现top命令下的系统CPU占用率几乎达到99.9%,然后重启系统之后问题未重现,第二天top一下CPU 20%, 第三天CPU占用率到30%,而且还有上升趋势。
从上面的情景描述看,显然是系统中某种消耗CPU资源的任务发生了泄露。通过pprof最终定位到系统的timer调度占用几乎所有的CPU时间。这引起了笔者的极大兴趣,于是笔者通过google神奇进行golang cpu timer相关的搜索。随后golang语言Api系统中CPU功耗优化300倍的过程这篇文章的博主给了笔者很大启发,应该是程序中某些地方的Tick的使用姿势不对,于是笔者开始了对time.After
和time.Tick
背后原理的追溯。
2. 定时器的使用
golang的定时器的使用非常简单,一般我们用的比较多的就是Timer和Ticker,如下所示:
//场景1:
for {
select {
case <- time.After(10 * time.Microsecond):
fmt.Println("hello timer")
}
}
//场景2:
for {
select {
case <- time.Tick(10 * time.Microsecond):
fmt.Println("hello, tick")
}
}
乍一看这两种调用方式都没有问题,而且短时间测试两种方式的效果看起来一样,然后如果测试时你使用top命令查看两种场景下的进程CPU占用率,你会大吃一惊,截图如下:
场景1-time_after 场景2-time_tick
从上面两图中可以看出After的用法比同用法下的Tick的CPU占用率小很多,而且tick的CPU占用率是很快就上升到100%的,如果这里的间隔时间设置稍微大一些可以更加明显的观察到Tick进程的CPU占用率上升的情况,那这是什么原因呢?
3.定时器的实现原理
记得哪里看过一句话,源码面前,了无秘密
。我们还是顺着Tick和After方法的源码探寻事情的真相吧.
- After的相关源码
//1.After方法, 创建了一个Timer对象并返回其chanel
func After(d Duration) <-chan Time {
return NewTimer(d).C
}
//2.NewTimer方法, 创建一个Timer对象并启动之,这里when方法是辅助定时时间的,sendTime用于向通道中返回Time对象,然后启动定时器
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
}
- Tick的相关源码
//1.创建Ticker对象,这里定时时间不允许小于0,否则可能会发生panic
func Tick(d Duration) <-chan Time {
if d <= 0 {
return nil
}
return NewTicker(d).C
}
//2.从NewTicker的源码来看,Ticker的基本数据结构和Timer类似,不同的是这里new的runtimeTimer加上了一个period的变量。
func NewTicker(d Duration) *Ticker {
if d <= 0 {
panic(errors.New("non-positive interval for NewTicker"))
}
// Give the channel a 1-element time buffer.
// If the client falls behind while reading, we drop ticks
// on the floor until the client catches up.
c := make(chan Time, 1)
t := &Ticker{
C: c,
r: runtimeTimer{
when: when(d),
period: int64(d),
f: sendTime,
arg: c,
},
}
startTimer(&t.r)
return t
}
从Timer和Ticker的源码中可以看出,其启动都是通过startTimer进行启动的,startTimer的实现在runtime/time.go中。
//1.startTimer将new的timer对象加入timer的堆数据结构中
//startTimer adds t to the timer heap.
//go:linkname startTimer time.startTimer
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}
func addtimer(t *timer) {
tb := t.assignBucket()
lock(&tb.lock)
tb.addtimerLocked(t)
unlock(&tb.lock)
}
// Add a timer to the heap and start or kick timerproc if the new timer is
// earlier than any of the others.
// Timers are locked.
func (tb *timersBucket) addtimerLocked(t *timer) {
// when must never be negative; otherwise timerproc will overflow
// during its delta calculation and never expire other runtime timers.
if t.when < 0 {
t.when = 1<<63 - 1
}
t.i = len(tb.t)
tb.t = append(tb.t, t)
siftupTimer(tb.t, t.i)
if t.i == 0 {
// siftup moved to top: new earliest deadline.
if tb.sleeping {
tb.sleeping = false
notewakeup(&tb.waitnote)
}
if tb.rescheduling {
tb.rescheduling = false
goready(tb.gp, 0)
}
}
if !tb.created {
tb.created = true
go timerproc(tb)
}
}
type timersBucket struct {
lock mutex
gp *g
created bool
sleeping bool
rescheduling bool
sleepUntil int64
waitnote note
t []*timer
}
定时器处理逻辑
func timerproc(tb *timersBucket) {
tb.gp = getg()
for {
lock(&tb.lock)
tb.sleeping = false
now := nanotime()
delta := int64(-1)
for {
if len(tb.t) == 0 { //无timer的情况
delta = -1
break
}
t := tb.t[0] //拿到堆顶的timer
delta = t.when - now
if delta > 0 { // 所有timer的时间都没有到期
break
}
if t.period > 0 { // t[0] 是ticker类型,调整其到期时间并调整timer堆结构
// leave in heap but adjust next time to fire
t.when += t.period * (1 + -delta/t.period)
siftdownTimer(tb.t, 0)
} else {
//Timer类型的定时器是单次的,所以这里需要将其从堆里面删除
// remove from heap
last := len(tb.t) - 1
if last > 0 {
tb.t[0] = tb.t[last]
tb.t[0].i = 0
}
tb.t[last] = nil
tb.t = tb.t[:last]
if last > 0 {
siftdownTimer(tb.t, 0)
}
t.i = -1 // mark as removed
}
f := t.f
arg := t.arg
seq := t.seq
unlock(&tb.lock)
if raceenabled {
raceacquire(unsafe.Pointer(t))
}
f(arg, seq) //调用定时器处理函数
lock(&tb.lock)
}
if delta < 0 || faketime > 0 {
// No timers left - put goroutine to sleep.
tb.rescheduling = true
goparkunlock(&tb.lock, "timer goroutine (idle)", traceEvGoBlock, 1)
continue
}
// At least one timer pending. Sleep until then.
tb.sleeping = true
tb.sleepUntil = now + delta
noteclear(&tb.waitnote)
unlock(&tb.lock)
notetsleepg(&tb.waitnote, delta)
}
}
以上便是定时器调用的主要逻辑,这里总结一下基本原理:
- 所有timer统一使用一个最小堆结构去维护,按照timer的when(到期时间)比较大小;
- timer处理线程从堆顶开始处理每个timer, 对于到期的timer, 如果其period>0, 则表明该timer 属于Ticker类型,调整其下次到期时间并调整其在堆中的位置,否则从堆中移除该timer;
- 调用该timer的处理函数以及其他相关工作;
4. 再论定时器的正确使用姿势
从第3节的源码中我们可以看到After和Tick其实是一个创建了一个单次的timer一个是创建了一个永久性的timer。因此场景2中Tick的用法会导致进程中创建无数个Tick,这最终导致了timer处理线程忙死。因此,使用Tick进行定时任务的话我们可以将Tick对象建在循环外面:
tick := time.Tick(10 * time.Microsecond)
for {
select {
case <- tick:
fmt.Printf("hello, tick 2")
}
}
其次golang的处理方式中也可以看出,go的timer的处理和用户端程序定义的间隔时间不一定完全精准,用户的回调函数执行时间越长单个timer对堆中其他邻近timer的影响越大。因此timer的回调函数一定是执行时间越短越好。