-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstage.go
80 lines (68 loc) · 1.14 KB
/
stage.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
package service
import (
"goio/msg"
"sync"
)
type Worker struct {
queue *queue.Sequence
running bool
wg *sync.WaitGroup
}
func NewWorker(qs int) *Worker {
return &Worker{
running: true,
wg: &sync.WaitGroup{},
queue: queue.NewSequece(uint64(qs)),
}
}
func (w *Worker) Run(h Handler) {
w.wg.Add(1)
go func() {
for w.running {
m, err := queue.Get()
if err != nil {
continue
}
h(m)
}
w.wg.Done()
}()
}
func (w *Worker) Wait() {
w.wg.Wait()
}
func (w *Worker) Stop() {
w.running = false
}
type Boss struct {
workers []*Worker
workerCount int
queueSize int
}
func NewBoss(wc, qs int, hander Handler) *Boss {
return &Boss{
workerCount: wc,
queueSize: qs,
}
}
func (s *Boss) Start(h Handler) {
for i := 0; i < s.workerCount; i++ {
worker := NewWorker(s.qs)
s.workers[i] = worker
h.SetHandlerId(i)
worker.Run(h)
}
}
func (s *Boss) Wait() {
for i := 0; i < s.workerCount; i++ {
s.workers[i].Wait()
}
}
func (s *Boss) Stop() {
for i := 0; i < s.workerCount; i++ {
s.workers[i].Stop()
}
}
func (s *Boss) Send(m msg.Message) {
s.works[m.HandlerId()%s.workerCount].queue.Put(m)
}