-
Notifications
You must be signed in to change notification settings - Fork 10
/
workerpool.go
71 lines (63 loc) · 1.19 KB
/
workerpool.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
package util
import (
"errors"
"runtime"
"sync"
"github.com/zhiqiangxu/util/logger"
"go.uber.org/zap"
)
// WorkerPool is pool of workers
type WorkerPool struct {
wg sync.WaitGroup
doneChan chan struct{}
workChan chan func()
once sync.Once
}
// NewWorkerPool is ctor for WorkerPool
func NewWorkerPool() *WorkerPool {
wp := &WorkerPool{doneChan: make(chan struct{}), workChan: make(chan func())}
wp.Start()
return wp
}
// Start worker pool
func (wp *WorkerPool) Start() {
n := runtime.NumCPU()
for i := 0; i < n; i++ {
GoFunc(&wp.wg, func() {
defer func() {
err := recover()
if err != nil {
logger.Instance().Error("workerPool", zap.Any("err", err))
}
}()
for {
select {
case f := <-wp.workChan:
f()
case <-wp.doneChan:
return
}
}
})
}
}
// Close the worker pool
func (wp *WorkerPool) Close() {
wp.once.Do(func() {
close(wp.doneChan)
wp.wg.Wait()
})
}
var (
// ErrWorkerPoolClosed when run on closed pool
ErrWorkerPoolClosed = errors.New("workerPool closed")
)
// Run a task
func (wp *WorkerPool) Run(f func()) error {
select {
case wp.workChan <- f:
return nil
case <-wp.doneChan:
return ErrWorkerPoolClosed
}
}