Blame view

src/components/timewheel/timerwheel.go 3.55 KB
6f0d72bd   zhangqijia   定时器功能完善优化
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
  package timewheel
  
  import (
  	"container/list"
  	"pro2d/src/common"
  	"pro2d/src/components/workpool"
  	"sync"
  	"sync/atomic"
  	"time"
  )
  
  //skynet的时间轮 + 协程池
  const (
  	TimeNearShift  = 8
  	TimeNear       = 1 << TimeNearShift
  	TimeLevelShift = 6
  	TimeLevel      = 1 << TimeLevelShift
  	TimeNearMask   = TimeNear - 1
  	TimeLevelMask  = TimeLevel - 1
  )
  
  type bucket struct {
  	expiration int32
  	timers *list.List
  
  	mu sync.Mutex
  }
  
  func newBucket() *bucket {
  	return &bucket{
  		expiration: -1,
  		timers:     list.New(),
  		mu: sync.Mutex{},
  	}
  }
  
  func (b*bucket) Add(t *timer)  {
  	b.mu.Lock()
  	defer b.mu.Unlock()
  
  	b.timers.PushBack(t)
  	//t.setBucket(b)
  	//t.element = e
  }
  
  func (b*bucket) Flush(reinsert func(t *timer))  {
  	b.mu.Lock()
  	defer b.mu.Unlock()
  
  	for e := b.timers.Front(); e != nil; {
  		next := e.Next()
  		reinsert(e.Value.(*timer))
  
  		b.timers.Remove(e)
  		e = next
  	}
  }
  
  type timer struct {
  	expiration	 uint32
  	f func()
  }
  
  var TimingWheel *TimeWheel
  
  func init()  {
  	TimingWheel = NewTimeWheel()
  	TimingWheel.Start()
  }
  type TimeWheel struct {
  	tick time.Duration
  	ticker *time.Ticker
  	near 			[TimeNear]*bucket
  	t				[4][TimeLevel]*bucket
  	time 			uint32
  
  	WorkPool *workpool.WorkPool
  	exit chan struct{}
  }
  
  func NewTimeWheel() *TimeWheel {
  	tw := &TimeWheel{
  		tick:         10*time.Millisecond,
  		time:         0,
  		WorkPool:     workpool.NewWorkPool(common.WorkerPoolSize, common.MaxTaskPerWorker),
2e0aa298   zhangqijia   update 每条连接新增一条协程...
86
  		exit:         make(chan struct{}),
6f0d72bd   zhangqijia   定时器功能完善优化
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
  	}
  	for i :=0; i < TimeNear; i++ {
  		tw.near[i] = newBucket()
  	}
  
  	for i :=0; i < 4; i++ {
  		for j :=0; j < TimeLevel; j++ {
  			tw.t[i][j] = newBucket()
  		}
  	}
  	return tw
  }
  
  func (tw *TimeWheel) add(t *timer) bool {
  	time := t.expiration
33ea26ab   zhangqijia   使用schema封装mongo
102
  	currentTime := atomic.LoadUint32(&tw.time)
6f0d72bd   zhangqijia   定时器功能完善优化
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
  	if time <= currentTime {
  		return false
  	}
  
  	if (time | TimeNearMask) == (currentTime | TimeNearMask) {
  		tw.near[time&TimeNearMask].Add(t)
  	}else {
  		i := 0
  		mask := TimeNear << TimeNearShift
  		for i=0; i < 3; i ++ {
  			if (time | uint32(mask - 1)) == (currentTime | uint32(mask - 1)) {
  				break
  			}
  			mask <<= TimeLevelShift
  		}
  
  		tw.t[i][((time>>(TimeNearShift + i*TimeLevelShift)) & TimeLevelMask)].Add(t)
  	}
  	return true
  }
  
  func (tw *TimeWheel) addOrRun(t *timer)  {
  	if !tw.add(t) {
  		workerID := int64(t.expiration) % tw.WorkPool.WorkerPoolSize
  		//将请求消息发送给任务队列
  		tw.WorkPool.TaskQueue[workerID] <- t.f
  	}
  }
  
  func (tw *TimeWheel) moveList(level, idx int)  {
  	current := tw.t[level][idx]
  	current.Flush(tw.addOrRun)
  }
  
  func (tw *TimeWheel) shift()  {
  	mask := TimeNear
33ea26ab   zhangqijia   使用schema封装mongo
139
  	ct := atomic.AddUint32(&tw.time, 1)
6f0d72bd   zhangqijia   定时器功能完善优化
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
  	if ct == 0 {
  		tw.moveList(3, 0)
  	}else {
  		time := ct >> TimeNearShift
  
  		i := 0
  		for (ct & uint32(mask-1)) == 0{
  			idx := time & TimeLevelMask
  			if idx != 0 {
  				tw.moveList(i, int(idx))
  				break
  			}
  
  			mask <<= TimeLevelShift
  			time >>= TimeLevelShift
  			i++
  		}
  	}
  }
  
  func (tw *TimeWheel) execute()  {
  	idx := tw.time & TimeNearMask
  	tw.near[idx].Flush(tw.addOrRun)
  }
  
  func (tw *TimeWheel) update()  {
  	tw.execute()
  	tw.shift()
  	tw.execute()
  }
  
  func (tw *TimeWheel) Start()  {
  	tw.ticker = time.NewTicker(tw.tick)
  	tw.WorkPool.StartWorkerPool()
  
  	go func() {
  		for  {
  			select {
  			case <- tw.ticker.C:
  				tw.update()
  			case <- tw.exit:
  				return
  			}
  		}
  	}()
  }
  
  func (tw *TimeWheel) Stop()  {
  	close(tw.exit)
  }
  
  func (tw *TimeWheel) afterFunc(expiration time.Duration, f func()) {
  	time := atomic.LoadUint32(&tw.time)
  	tw.addOrRun(&timer{
  		expiration: uint32(expiration / tw.tick) + time,
  		f:          f,
  	})
  }
  
  func TimeOut(expire time.Duration, f func()) {
  	TimingWheel.afterFunc(expire, f)
2e0aa298   zhangqijia   update 每条连接新增一条协程...
201
202
203
204
  }
  
  func StopTimer()  {
  	TimingWheel.Stop()
6f0d72bd   zhangqijia   定时器功能完善优化
205
  }