forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.go
108 lines (74 loc) · 1.39 KB
/
queue.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
package cellnet
import (
"runtime/debug"
"sync"
)
type EventQueue interface {
StartLoop()
StopLoop(result int)
// 等待退出
Wait() int
// 投递事件, 通过队列到达消费者端
Post(callback func())
// 是否捕获异常
EnableCapturePanic(v bool)
}
type evQueue struct {
queue chan func()
endSignal sync.WaitGroup
capturePanic bool
result int
}
func (self *evQueue) EnableCapturePanic(v bool) {
self.capturePanic = v
}
// 派发到队列
func (self *evQueue) Post(callback func()) {
if callback == nil {
return
}
self.queue <- callback
}
func (self *evQueue) protectedCall(callback func()) {
if callback == nil {
return
}
if self.capturePanic {
defer func() {
if err := recover(); err != nil {
debug.PrintStack()
}
}()
}
callback()
}
func (self *evQueue) StartLoop() {
self.endSignal.Add(1)
go func() {
for callback := range self.queue {
if callback == nil {
break
}
self.protectedCall(callback)
}
self.endSignal.Done()
}()
}
func (self *evQueue) StopLoop(result int) {
self.queue <- nil
self.result = result
}
func (self *evQueue) Wait() int {
self.endSignal.Wait()
return self.result
}
const DefaultQueueSize = 100
func NewEventQueue() EventQueue {
return NewEventQueueByLen(DefaultQueueSize)
}
func NewEventQueueByLen(l int) EventQueue {
self := &evQueue{
queue: make(chan func(), l),
}
return self
}