-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspawner.go
61 lines (50 loc) · 882 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
56
57
58
59
60
61
package archer
import (
"context"
"sync"
)
func newSpawner(ctx context.Context, errChan chan<- error) *spawn {
ctx, cancel := context.WithCancel(ctx)
return &spawn{
wg: &sync.WaitGroup{},
ctx: ctx,
shutdown: cancel,
errChan: errChan,
}
}
type Spawner interface {
Spawn(runner)
Wait()
Shutdown()
Done() <-chan struct{}
}
type spawn struct {
wg *sync.WaitGroup
ctx context.Context
shutdown func()
errChan chan<- error
}
type runner interface {
Run(ctx context.Context, errChan chan<- error)
}
func (s *spawn) Spawn(runner runner) {
s.wg.Add(1)
go func() {
defer s.wg.Done()
runner.Run(s.ctx, s.errChan)
}()
}
func (s *spawn) Wait() {
s.wg.Wait()
}
func (s *spawn) Shutdown() {
s.shutdown()
}
func (s *spawn) Done() <-chan struct{} {
c := make(chan struct{})
go func() {
<-s.ctx.Done()
c <- struct{}{}
}()
return c
}