lens @ c2d666b43477ea7042b574ad940c508216cb0e83

 1package worker
 2
 3import (
 4	"context"
 5	"errors"
 6	"fmt"
 7	"sync"
 8)
 9
10type (
11	// Worker should watch for context
12	Worker interface {
13		Start(context.Context) error
14	}
15
16	Work struct {
17		Name   string
18		Worker Worker
19	}
20
21	WorkerPool struct {
22		workers []*Work
23	}
24)
25
26func NewWorkerPool() *WorkerPool {
27	return &WorkerPool{}
28}
29
30func (self *WorkerPool) AddWorker(name string, worker Worker) {
31	self.workers = append(self.workers, &Work{
32		Name:   name,
33		Worker: worker,
34	})
35}
36
37func (self *WorkerPool) Start(ctx context.Context) {
38	var wg sync.WaitGroup
39
40	wg.Add(len(self.workers))
41
42	for _, w := range self.workers {
43		go func(w *Work) {
44			defer wg.Done()
45			if err := w.Worker.Start(ctx); err != nil && !errors.Is(err, context.Canceled) {
46				fmt.Println("Processes finished, error", w.Name, err.Error())
47			} else {
48				fmt.Println(w.Name, "done")
49			}
50		}(w)
51	}
52
53	wg.Wait()
54}