-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
81 lines (69 loc) · 1.38 KB
/
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
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
package routinepool
import (
"fmt"
"runtime/debug"
"sync"
"sync/atomic"
)
var workerPool sync.Pool
func init() {
workerPool.New = newWorker
}
type worker struct {
pool *pool
}
func newWorker() interface{} {
return &worker{}
}
func (w *worker) run() {
go func() {
for {
var t *task
w.pool.taskLock.Lock()
if w.pool.taskHead != nil {
t = w.pool.taskHead
w.pool.taskHead = w.pool.taskHead.next
cnt := atomic.AddInt32(&w.pool.taskCount, -1)
_metricQueueSize.Set(float64(cnt), w.pool.name)
}
if t == nil {
// if there's no task to do, exit
w.close()
w.pool.taskLock.Unlock()
w.Recycle()
return
}
w.pool.taskLock.Unlock()
// check context before doing task
select {
case <-t.ctx.Done():
w.pool.panicHandler(t.ctx, fmt.Errorf("[routinepool] task cancel: %s error: %w", w.pool.name, t.ctx.Err()))
t.Recycle()
continue
default:
}
func() {
defer func() {
if r := recover(); r != nil {
if w.pool.panicHandler != nil {
w.pool.panicHandler(t.ctx, fmt.Errorf("[routinepool] panic in pool: %s: %v: %s", w.pool.name, r, debug.Stack()))
}
}
}()
t.f(t.ctx)
_metricCount.Inc(w.pool.name)
}()
t.Recycle()
}
}()
}
func (w *worker) close() {
w.pool.decWorkerCount()
}
func (w *worker) zero() {
w.pool = nil
}
func (w *worker) Recycle() {
w.zero()
workerPool.Put(w)
}