forked from rfyiamcool/go-timewheel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timewheel_pool.go
55 lines (45 loc) · 994 Bytes
/
timewheel_pool.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
package timewheel
import (
"math/rand"
"sync/atomic"
"time"
)
type TimeWheelPool struct {
pool []*TimeWheel
size int64
incr int64 // not need for high accuracy
}
func NewTimeWheelPool(size int, tick time.Duration, bucketsNum int, options ...optionCall) (*TimeWheelPool, error) {
twp := &TimeWheelPool{
pool: make([]*TimeWheel, size),
size: int64(size),
}
for index := 0; index < bucketsNum; index++ {
tw, err := NewTimeWheel(tick, bucketsNum, options...)
if err != nil {
return twp, err
}
twp.pool[index] = tw
}
return twp, nil
}
func (tp *TimeWheelPool) Get() *TimeWheel {
incr := atomic.AddInt64(&tp.incr, 1)
idx := incr % tp.size
return tp.pool[idx]
}
func (tp *TimeWheelPool) GetRandom() *TimeWheel {
rand.Seed(time.Now().UnixNano())
idx := rand.Int63n(tp.size)
return tp.pool[idx]
}
func (tp *TimeWheelPool) Start() {
for _, tw := range tp.pool {
tw.Start()
}
}
func (tp *TimeWheelPool) Stop() {
for _, tw := range tp.pool {
tw.Stop()
}
}