/
spawner.go
55 lines (46 loc) · 911 Bytes
/
spawner.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
package workers
import (
"context"
"sync"
)
func newSpawner(ctx context.Context, errChan chan<- error) spawner {
ctx, cancel := context.WithCancel(ctx)
return spawner{
wg: &sync.WaitGroup{},
ctx: ctx,
shutdown: cancel,
errChan: errChan,
}
}
// spawner keeps track of running routines
type spawner struct {
wg *sync.WaitGroup
ctx context.Context
shutdown func()
errChan chan<- error
}
//go:generate mockgen -destination=./runner_mock_test.go -package=workers -source=spawner.go
type runner interface {
Run(context.Context, chan<- error)
}
func (s spawner) Spawn(r runner) {
s.wg.Add(1)
go func() {
r.Run(s.ctx, s.errChan)
s.wg.Done()
}()
}
func (s spawner) Wait() {
s.wg.Wait()
}
func (s spawner) Shutdown() {
s.shutdown()
}
func (s spawner) Done() <-chan struct{} {
c := make(chan struct{})
go func() {
<-s.ctx.Done()
c <- struct{}{}
}()
return c
}