-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_worker.go
56 lines (46 loc) · 912 Bytes
/
queue_worker.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
package toolkit
import (
"sync"
)
type QueueWorker struct {
workers int
quit chan struct{}
wg *sync.WaitGroup
jobsChan chan interface{}
onWork WorkAction
}
type WorkAction func(int)
func NewQueueWorker(workers int, onWork WorkAction) *QueueWorker {
return &QueueWorker{
workers: workers,
quit: make(chan struct{}),
wg: new(sync.WaitGroup),
jobsChan: make(chan interface{}, 4*workers),
onWork: onWork,
}
}
func (sl *QueueWorker) Start() {
for i := 0; i < sl.workers; i++ {
go func(index int) {
sl.Work(index)
}(i)
}
}
func (sl *QueueWorker) Stop() {
close(sl.quit)
sl.wg.Wait()
}
func (sl *QueueWorker) Enqueue(job interface{}) {
sl.jobsChan <- job
}
func (sl *QueueWorker) Work(index int) {
defer func() {
if r := recover(); r != nil {
// todo: need log here
sl.Work(index)
}
}()
sl.wg.Add(1)
defer sl.wg.Done()
sl.onWork(index)
}