-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_work_pool.go
86 lines (71 loc) · 1.36 KB
/
event_work_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
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
package go_epoll
import "sync"
type EventTask struct {
fn EventHandler
ev *Event
}
func NewTask(fn EventHandler, ev *Event) *EventTask {
return &EventTask{
fn: fn,
ev: ev,
}
}
func (t *EventTask) Exec() {
t.fn(t.ev)
}
type EventWorkPool struct {
workCount int
taskQueue chan *EventTask
wg sync.WaitGroup
stop chan struct{}
onPanic func(msg interface{})
}
func NewEventWorkPool(workCount int) *EventWorkPool {
return &EventWorkPool{
workCount: workCount,
taskQueue: make(chan *EventTask),
wg: sync.WaitGroup{},
stop: make(chan struct{}),
}
}
func (wp *EventWorkPool) Run() {
wp.wg.Add(wp.workCount)
for i := 0; i < wp.workCount; i++ {
go func() {
defer func() {
if err := recover(); err != nil {
if wp.onPanic != nil {
wp.onPanic(err)
}
}
}()
defer wp.wg.Done()
for {
select {
case <-wp.stop:
return
case task, ok := <-wp.taskQueue:
if !ok {
return
}
task.Exec()
}
}
}()
}
wp.wg.Wait()
}
func (wp *EventWorkPool) Close() {
wp.stop <- struct{}{}
close(wp.stop)
close(wp.taskQueue)
}
func (wp *EventWorkPool) OnPanic(fn func(msg interface{})) {
wp.onPanic = fn
}
func (wp *EventWorkPool) PushTask(t *EventTask) {
wp.taskQueue <- t
}
func (wp *EventWorkPool) PushTaskFunc(fn EventHandler, ev *Event) {
wp.taskQueue <- NewTask(fn, ev)
}