-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
80 lines (70 loc) · 1.35 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
package gpool
import (
"context"
"sync"
"sync/atomic"
)
type worker struct {
ctx context.Context
processors []IProcessor
status uint32
cancel context.CancelFunc
processorWg sync.WaitGroup
inputCh chan iTaskWithHandler
}
func (w *worker) addProcessor(p IProcessor) {
w.processors = append(w.processors, p)
w.processorWg.Add(1)
r := p.register()
go func() {
defer func() {
w.processorWg.Done()
r.Cancel()
}()
for {
select {
case <-w.ctx.Done():
return
case t := <-r.C():
// emit the job to the worker input channel
w.inputCh <- t
}
}
}()
}
func (w *worker) addProcessors(ps []IProcessor) {
for _, p := range ps {
w.addProcessor(p)
}
}
func (w *worker) loop() {
for {
select {
case <-w.ctx.Done():
return
case t := <-w.inputCh:
atomic.SwapUint32(&w.status, 0)
t.execute(w.ctx)
atomic.SwapUint32(&w.status, 1)
}
}
}
func (w *worker) isIdle() bool {
return atomic.LoadUint32(&w.status) == 0
}
func (w *worker) isBusy() bool {
return atomic.LoadUint32(&w.status) == 1
}
func (w *worker) stop() {
w.cancel()
w.processorWg.Wait()
}
func newWorker(ctx context.Context, processors []IProcessor) *worker {
wCtx, cancel := context.WithCancel(ctx)
return &worker{
processors: processors,
ctx: wCtx,
cancel: cancel,
inputCh: make(chan iTaskWithHandler, 1),
}
}