go
go copied to clipboard
timingwheel.go:(TimingWheel)After()函数中index计算不正确
siddontang,在查看你的时间轮代码时候,觉得(TimingWheel)After()函数中index计算不正确,为了验证猜想,我写了如下测试用例:
- https://github.com/AlexStocks/go-practice/blob/master/time/siddontang_time_wheel.go
输出是:expect time cost 100s, while real time cost is 110 s. 显然,当运行次数越多,你的timingwheel的时间误差将越多,我给你修正后的(TimingWheel)After()函数代码如下: func (w *TimingWheel) After(timeout time.Duration) <-chan struct{} { if timeout >= w.maxTimeout { panic("timeout too much, over maxtimeout") }
index := int(timeout / w.interval)
if 0 < index {
index--
}
w.Lock()
index = (w.pos + index) % len(w.cs)
b := w.cs[index]
w.Unlock()
return b
}
再次运行我的测试用例后,输出如下:
expect time cost 100s, while real time cost is 100 s.
This output is perfect.