-
Notifications
You must be signed in to change notification settings - Fork 0
/
stop.go
89 lines (73 loc) · 1.4 KB
/
stop.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package stop
import "sync"
type Interface interface {
Start()
Stop()
}
// Struct is abstract class with Start/Stop methods
type Struct struct {
sync.RWMutex
exit chan struct{}
wg sync.WaitGroup
Go func(callable func(exit chan struct{}))
WithExit func(callable func(exit chan struct{}))
}
// Start ...
func (s *Struct) Start() {
s.StartFunc(func() error { return nil })
}
// Stop ...
func (s *Struct) Stop() {
s.StopFunc(func() {})
}
// StartFunc ...
func (s *Struct) StartFunc(startProcedure func() error) error {
s.Lock()
defer s.Unlock()
// already started
if s.exit != nil {
return nil
}
exit := make(chan struct{})
s.exit = exit
s.Go = func(callable func(exit chan struct{})) {
s.wg.Add(1)
go func() {
callable(exit)
s.wg.Done()
}()
}
s.WithExit = func(callable func(exit chan struct{})) {
callable(exit)
}
err := startProcedure()
// stop all if start failed
if err != nil {
s.doStop(func() {})
}
return err
}
func (s *Struct) doStop(callable func()) {
// already stopped
if s.exit == nil {
return
}
close(s.exit)
callable()
s.wg.Wait()
s.exit = nil
s.Go = func(callable func(exit chan struct{})) {}
s.WithExit = func(callable func(exit chan struct{})) {
callable(nil)
}
}
// StopFunc ...
func (s *Struct) StopFunc(callable func()) {
s.Lock()
defer s.Unlock()
// already stopped
if s.exit == nil {
return
}
s.doStop(callable)
}