blob: 18cc0e25c15a57d778a806275f6fa354b637d8c0 (
plain)
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
|
package worker
import (
"context"
"errors"
"fmt"
"sync"
)
type (
// Worker should watch for context
Worker interface {
Start(context.Context) error
}
Work struct {
Name string
Worker Worker
}
WorkerPool struct {
workers []*Work
wg sync.WaitGroup
}
)
func NewWorkerPool() *WorkerPool {
return &WorkerPool{}
}
func (self *WorkerPool) AddWorker(name string, worker Worker) {
self.workers = append(self.workers, &Work{
Name: name,
Worker: worker,
})
}
func (self *WorkerPool) Start(ctx context.Context) {
self.wg.Add(len(self.workers))
for _, w := range self.workers {
go func(w *Work) {
defer self.wg.Done()
if err := w.Worker.Start(ctx); err != nil && !errors.Is(err, context.Canceled) {
fmt.Println("Processes finished, error", w.Name, err.Error())
} else {
fmt.Println(w.Name, "done")
}
}(w)
}
}
func (self *WorkerPool) Wait() {
self.wg.Wait()
}
|