forked from davyxu/cellnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.go
105 lines (73 loc) · 1.42 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
package cellnet
import (
"runtime/debug"
"time"
)
type EventQueue interface {
StartLoop()
StopLoop(result int)
// 等待退出
Wait() int
// 投递事件, 通过队列到达消费者端
Post(callback func())
// 延时投递
DelayPost(dur time.Duration, callback func())
}
type queueData struct {
data interface{}
}
type evQueue struct {
queue chan func()
exitSignal chan int
capturePanic bool
}
// 派发到队列
func (self *evQueue) Post(callback func()) {
if callback == nil {
return
}
self.queue <- callback
}
func (self *evQueue) DelayPost(dur time.Duration, callback func()) {
time.AfterFunc(dur, func() {
self.Post(callback)
})
}
func (self *evQueue) protectedCall(callback func()) {
if callback == nil {
return
}
if self.capturePanic {
defer func() {
if err := recover(); err != nil {
//log.Fatalln(err)
debug.PrintStack()
}
}()
}
callback()
}
func (self *evQueue) StartLoop() {
go func() {
for callback := range self.queue {
self.protectedCall(callback)
}
}()
}
func (self *evQueue) StopLoop(result int) {
self.exitSignal <- result
}
func (self *evQueue) Wait() int {
return <-self.exitSignal
}
const DefaultQueueSize = 100
func NewEventQueue() EventQueue {
return NewEventQueueByLen(DefaultQueueSize)
}
func NewEventQueueByLen(l int) EventQueue {
self := &evQueue{
queue: make(chan func(), l),
exitSignal: make(chan int),
}
return self
}