-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue_callbacks.go
142 lines (102 loc) · 2.17 KB
/
queue_callbacks.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
package eventbus
import (
"sync"
"sync/atomic"
"time"
)
type FnCallback func()
type QueueCallbacks struct {
isRunning bool
startOnce sync.Once
waitingCallbacks uint32
queue []FnCallback
mtx *sync.Mutex
runnerFn *PorcessFn
runnerLimit int
}
func NewQueue(runnerLimit int) *QueueCallbacks {
q := &QueueCallbacks{
startOnce: sync.Once{},
queue: make([]FnCallback, runnerLimit),
mtx: &sync.Mutex{},
runnerFn: NewRunnerFn(time.Millisecond*10, runnerLimit),
runnerLimit: runnerLimit,
waitingCallbacks: 0,
}
return q
}
func (q *QueueCallbacks) Set(fn FnCallback) {
atomic.AddUint32(&q.waitingCallbacks, 1)
q.fitOrExtand(fn)
q.start()
}
func (q *QueueCallbacks) fitOrExtand(fn FnCallback) {
q.mtx.Lock()
defer q.mtx.Unlock()
for i := len(q.queue) - 1; i >= 0; i-- {
if q.queue[i] == nil {
q.queue[i] = fn
return
}
}
q.queue = append(q.queue, fn)
}
func (q *QueueCallbacks) WaitingCallbacks() uint32 {
return atomic.LoadUint32(&q.waitingCallbacks)
}
const (
timeTicker = 1 * time.Second
)
func (q *QueueCallbacks) start() {
if q.isRunning {
return
}
q.isRunning = true
q.startOnce.Do(func() {
//Consumer
go func() {
defer func() {
if err := recover(); err != nil {
}
q.resetQueue()
}()
var (
fn FnCallback
i int
lenQ int
timeEndQueue *time.Time
loopCheck int
)
for q.isRunning {
i = 0
lenQ = len(q.queue)
for ; i < lenQ; i++ {
if q.queue[i] == nil {
continue
}
if timeEndQueue != nil {
timeEndQueue = nil
}
fn, q.queue[i] = q.queue[i], fn
q.runnerFn.Next(fn)
fn = nil
}
if timeEndQueue == nil {
t := time.Now()
timeEndQueue = &t
loopCheck = 0
} else if loopCheck > 6 && timeEndQueue.After(time.Now().Add(-1*timeTicker)) {
return
}
loopCheck++
time.Sleep(time.Nanosecond * 50)
}
}()
})
}
func (q *QueueCallbacks) resetQueue() {
q.queue = make([]FnCallback, q.runnerLimit)
q.startOnce = sync.Once{}
q.isRunning = false
atomic.SwapUint32(&q.waitingCallbacks, 0)
}