-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtimerwheel.go
62 lines (54 loc) · 1.25 KB
/
timerwheel.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
package timer
import "sync"
// TimeWheel 时间轮
type TimeWheel struct {
sync.RWMutex
TS [][]*TimerSlice
Index uint
}
// AddToIndex 给当前时间轮添加点
func (tw *TimeWheel) AddToIndex(index uint, ts *TimerSlice) bool {
tw.Lock()
defer tw.Unlock()
if index > uint(len(tw.TS)) {
return false
}
tw.TS[index] = append(tw.TS[index], ts)
return true
}
func (tw *TimeWheel) unsafeRemove(index, at uint) bool {
if index > uint(len(tw.TS)) || at > uint(len(tw.TS[index])) {
return false
}
tw.TS[index] = append(tw.TS[index][:at], tw.TS[index][at+1:]...)
return true
}
// RemoveWithID 删除某个ID
func (tw *TimeWheel) RemoveWithID(id uint64) bool {
tw.Lock()
defer tw.Unlock()
for index := 0; index < len(tw.TS); index++ {
t := tw.TS[index]
for i := 0; i < len(t); i++ {
if t[i].id == id {
tw.unsafeRemove(uint(index), uint(i))
return true
}
}
}
return false
}
// CurTimerSliceAndClear 获取当前时间片,且清空时间片
func (tw *TimeWheel) CurTimerSliceAndClear() []*TimerSlice {
tw.Lock()
tmp := tw.TS[tw.Index]
tw.TS[tw.Index] = []*TimerSlice{}
tw.Unlock()
return tmp
}
// Tick 时间轮自增一次
func (tw *TimeWheel) Tick() {
tw.Lock()
tw.Index = (tw.Index + 1) % uint(len(tw.TS))
tw.Unlock()
}