-
Notifications
You must be signed in to change notification settings - Fork 2
/
ticker.go
456 lines (384 loc) · 9.89 KB
/
ticker.go
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
// Package tik implements Hierarchical Timing Wheels.
package tik
import (
"math"
"runtime"
"sync"
"sync/atomic"
"unsafe"
list "github.com/andy2046/gopie/pkg/dll"
"github.com/andy2046/gopie/pkg/log"
"github.com/andy2046/maths"
"golang.org/x/sys/cpu"
)
const (
cacheLinePadSize = unsafe.Sizeof(cpu.CacheLinePad{})
)
var (
logger = log.NewLogger(func(c *log.Config) error {
c.Level = log.DEBUG
c.Prefix = "<tik>\t"
return nil
})
)
type (
// Ticker progress the timing wheels.
Ticker struct {
_ [cacheLinePadSize]byte
closed uint64
_ [cacheLinePadSize - 8%cacheLinePadSize]byte
curtime uint64
wheelLen uint64 // 1<<nWheelBit
wheelMax uint64 // wheelLen-1
wheelMask uint64 // wheelLen-1
timeoutMax uint64 // 1<<(nWheel*nWheelBit)-1
// nWheel is the number of wheels. nWheelBit * nWheel is the number of
// value bits used by all the wheels.
nWheel uint8
// nWheelBit is the number of value bits mapped in each wheel.
// nWheelBit can NOT be larger than 6 bits because 2^6 -> 64 is the largest
// number of slots which can be tracked.
nWheelBit uint8
closer chan struct{}
timer Timer
expired *list.List
wheelz []*wheel
once sync.Once
}
wheel struct {
_ [cacheLinePadSize]byte
pending uint64
_ [cacheLinePadSize - 8%cacheLinePadSize]byte
slot []*list.List
}
// Config used to init Ticker.
Config struct {
// number of value bits mapped in each wheel.
WheelBitNum uint8
// number of wheels.
WheelNum uint8
// Timer to progress the timing wheel.
Timer Timer
}
// Option applies config to Ticker Config.
Option = func(*Config)
)
var (
// DefaultConfig is the default Ticker Config.
DefaultConfig = Config{
WheelBitNum: 6,
WheelNum: 4,
Timer: nil,
}
)
// New initiates a new Ticker.
func New(options ...Option) *Ticker {
tConfig := DefaultConfig
setOption(&tConfig, options...)
if tConfig.WheelBitNum < 3 || tConfig.WheelBitNum > 6 {
panic("WheelBitNum should be in range [3, 6]")
}
switch tConfig.WheelNum {
case 2:
case 4:
case 8:
default:
panic("WheelNum should be in set {2, 4, 8}")
}
if tConfig.Timer == nil {
tConfig.Timer = NewTimer(100) // 100 millisecond interval
}
tk := &Ticker{}
tk.init(tConfig.WheelBitNum, tConfig.WheelNum, tConfig.Timer)
return tk
}
func (tk *Ticker) init(nWheelBit, nWheel uint8, timer Timer) {
tk.nWheel = nWheel
tk.nWheelBit = nWheelBit
tk.wheelLen = 1 << nWheelBit
tk.wheelMax = 1<<nWheelBit - 1
tk.wheelMask = 1<<nWheelBit - 1
tk.timeoutMax = 1<<(nWheel*nWheelBit) - 1
tk.closer = make(chan struct{})
tk.timer = timer
tk.curtime = timer.Now()
tk.expired = list.New()
tk.wheelz = make([]*wheel, tk.nWheel)
for i := range tk.wheelz {
slot := make([]*list.List, tk.wheelLen)
for j := range slot {
slot[j] = list.New()
}
tk.wheelz[i] = &wheel{
pending: 0,
slot: slot,
}
}
go func() {
for {
select {
case <-tk.closer:
return
case absolute := <-tk.timer.Step():
tk.update(absolute)
}
}
}()
go func() {
defer func() {
if r := recover(); r != nil {
var buf [4096]byte
n := runtime.Stack(buf[:], false)
logger.Error(r)
logger.Error(string(buf[:n]))
}
}()
for {
select {
case <-tk.closer:
return
default:
}
to := tk.getExpired()
if to != nil && to.callbk != nil {
to.callbk()
}
}
}()
}
// Schedule creates a one-shot action that executed after the given delay.
// `delay` is the time from now to delay execution,
// the time unit of the delay depends on the Timer provided, default is millisecond.
// `cb` is the task to execute.
// it returns `nil` if Ticker is closed.
func (tk *Ticker) Schedule(delay uint64, cb Callback) *Timeout {
if tk.IsClosed() {
logger.Error("Ticker closed, no more Schedule is allowed")
return nil
}
to := newTimeout(cb)
tk.add(to, delay)
return to
}
// Cancel the Timeout scheduled if it has not yet expired.
func (tk *Ticker) Cancel(to *Timeout) {
if to == nil {
return
}
tk.del(to)
}
// Close stop processing any task,
// whether it is pending or expired.
func (tk *Ticker) Close() {
tk.once.Do(func() {
close(tk.closer)
})
atomic.CompareAndSwapUint64(&tk.closed, 0, 1)
tk.timer.Stop()
}
// IsClosed returns true if closed, false otherwise.
func (tk *Ticker) IsClosed() bool {
return atomic.LoadUint64(&tk.closed) == 1
}
func (tk *Ticker) update(curtime uint64) {
curtimeTK := atomic.LoadUint64(&tk.curtime)
elapsed := curtime - curtimeTK
todo := list.New()
// looping over every wheel, better to keep number of wheelz smallish
for i := uint8(0); i < tk.nWheel; i++ {
pending := uint64(0)
iWheelBit := i * tk.nWheelBit
// calculate the slots expiring in this wheel
//
// if the elapsed time is greater than the maximum period of
// the wheel, mark every position as expiring.
//
// otherwise, to determine the expired slots fill in all the
// bits between the last slot processed and the current
// slot, inclusive of the last slot.
//
// if a wheel rolls over, force a tick of the next higher
// wheel.
if (elapsed >> iWheelBit) > tk.wheelMax {
pending = math.MaxUint64
} else {
elapsedTmp := tk.wheelMask & (elapsed >> iWheelBit)
elapsedTmpShift := uint64((1 << elapsedTmp) - 1)
oslot := tk.wheelMask & (curtimeTK >> iWheelBit)
pending = rotl(elapsedTmpShift, int(oslot))
nslot := tk.wheelMask & (curtime >> iWheelBit)
pending |= rotr(rotl(elapsedTmpShift, int(nslot)), int(elapsedTmp))
pending |= (1 << nslot)
}
pp := &tk.wheelz[i].pending
for pending&atomic.LoadUint64(pp) != 0 {
islot := ctz(pending & tk.wheelz[i].pending)
l := tk.wheelz[i].slot[islot]
for !l.Empty() {
ee := l.PopLeft()
if e, ok := ee.(*Timeout); ok {
todo.PushRight(e)
}
}
for l.Empty() {
p := atomic.LoadUint64(pp)
if casPending(pp, p, p&^(1<<uint(islot))) { // race
break
}
}
}
if 0x1&pending == 0 {
// break if not wrapping around end of wheel.
break
}
// if continuing, the next wheel must tick at least once.
elapsed = maths.Uint64Var.Max(elapsed, tk.wheelLen<<iWheelBit)
}
atomic.StoreUint64(&tk.curtime, curtime)
for !todo.Empty() {
to := todo.PopLeft().(*Timeout)
to.m.Lock()
to.pending = nil
to.element = nil // unlink to List
to.m.Unlock()
tk.sched(to, to.expires, curtime)
}
}
func (tk *Ticker) add(to *Timeout, timeout uint64) {
curtime := atomic.LoadUint64(&tk.curtime)
tk.sched(to, curtime+timeout, curtime)
}
func (tk *Ticker) sched(to *Timeout, expires, curtime uint64) {
tk.del(to)
if expires > curtime {
rem := tk.rem(expires, curtime)
iwheel := tk.wheel(rem)
islot := tk.slot(iwheel, expires)
to.m.Lock()
to.iwheel, to.islot = iwheel, islot
to.pending = tk.wheelz[iwheel].slot[islot]
to.element = to.pending.PushRight(to) // link to List
to.expires = expires
to.papa = tk
pending := to.pending
to.m.Unlock()
for !pending.Empty() {
pp := &tk.wheelz[iwheel].pending
p := atomic.LoadUint64(pp)
if p&(1<<islot) != 0 {
break
}
if casPending(pp, p, p|(1<<islot)) { // race
break
}
}
} else {
to.m.Lock()
to.expires = expires
to.papa = tk
to.pending = tk.expired
to.element = to.pending.PushRight(to)
to.m.Unlock()
}
}
func (tk *Ticker) del(to *Timeout) {
to.m.Lock()
defer to.m.Unlock()
if to.pending != nil {
if to.element != nil {
to.pending.Remove(to.element)
}
for {
if to.pending != tk.expired && to.pending.Empty() &&
to.iwheel != math.MaxUint8 && to.islot != math.MaxUint8 {
pp := &tk.wheelz[to.iwheel].pending
p := atomic.LoadUint64(pp)
if casPending(pp, p, p&^(1<<to.islot)) { // race
break
}
} else {
break
}
}
to.pending = nil
to.papa = nil
to.element = nil
}
}
func (tk *Ticker) wheel(timeout uint64) uint8 {
// must be timeout != 0, so fls input is nonzero
return uint8(fls(maths.Uint64Var.Min(timeout, tk.timeoutMax))-1) / tk.nWheelBit
}
func (tk *Ticker) slot(wheel uint8, expires uint64) uint8 {
i := uint64(1)
if wheel == 0 {
i = 0
}
return uint8(tk.wheelMask & ((expires >> (wheel * tk.nWheelBit)) - i))
}
func (tk *Ticker) rem(expires, curtime uint64) uint64 {
return expires - curtime
}
func (tk *Ticker) getExpired() *Timeout {
if tk.expired.Empty() {
return nil
}
to := tk.expired.PopLeft().(*Timeout)
to.m.Lock()
to.pending = nil
to.papa = nil
to.element = nil
to.m.Unlock()
return to
}
/*
// calculate the interval before needing to process any timeouts pending on
// any wheel.
//
// this might return a timeout value sooner than any installed timeout if
// only higher-order wheels have timeouts pending. It only known when to
// process a wheel, not precisely when a timeout is scheduled.
func (tk *Ticker) interval() uint64 {
var timeoutTmp, relmask, pending uint64
var timeout uint64 = math.MaxUint64
var curtime = atomic.LoadUint64(&tk.curtime)
for i := uint8(0); i < tk.nWheel; i++ {
pending = atomic.LoadUint64(&tk.wheelz[i].pending)
if pending != 0 {
iWheelBit := i * tk.nWheelBit
slot := tk.wheelMask & (curtime >> iWheelBit)
j := 1
if i == 0 {
j = 0
}
timeoutTmp = uint64(ctz(rotr(pending, int(slot)))+j) << iWheelBit
timeoutTmp -= (relmask & curtime)
timeout = maths.Uint64Var.Min(timeoutTmp, timeout)
}
relmask <<= tk.nWheelBit
relmask |= tk.wheelMask
}
return timeout
}
*/
// AnyExpired returns true if expiry queue is not empty, false otherwise.
func (tk *Ticker) AnyExpired() bool {
return !tk.expired.Empty()
}
// AnyPending returns true if there is task in wheels, false otherwise.
func (tk *Ticker) AnyPending() bool {
var p uint64
for _, w := range tk.wheelz {
p |= atomic.LoadUint64(&w.pending) // race
}
return p != 0
}
// setOption takes one or more Option function and applies them in order to Ticker Config.
func setOption(p *Config, options ...func(*Config)) {
for _, opt := range options {
opt(p)
}
}
func casPending(p *uint64, c, n uint64) bool {
return atomic.CompareAndSwapUint64(p, c, n)
}