-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.go
More file actions
65 lines (60 loc) · 1.08 KB
/
worker.go
File metadata and controls
65 lines (60 loc) · 1.08 KB
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
package concurrent
import (
"github.com/google/uuid"
"os"
"os/signal"
"sync"
"syscall"
)
type worker struct {
in chan *item
out chan *item
errChan chan error
id string
count int
kill chan os.Signal
}
func newWorker() *worker {
id, _ := uuid.NewRandom()
kill := make(chan os.Signal, 1)
signal.Notify(kill, os.Interrupt, syscall.SIGKILL, syscall.SIGTERM)
return &worker{
in: make(chan *item),
errChan: make(chan error, 1),
id: id.String(),
kill: kill,
}
}
func (w *worker) run(wg *sync.WaitGroup, limit int, process processFunc, continueOnError bool) {
w.out = make(chan *item, limit)
wg.Add(1)
go func() {
defer wg.Done()
defer close(w.out)
defer close(w.errChan)
for {
select {
case raw, canRead := <-w.in:
if !canRead {
return
}
v, err := process(raw.value)
if err != nil {
if continueOnError {
continue
}
w.errChan <- err
return
}
raw.value = v
w.out <- raw
case <-w.kill:
return
}
}
}()
}
func (w *worker) add(item *item) {
w.count += 1
w.in <- item
}