-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlife.go
61 lines (52 loc) · 1.02 KB
/
life.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 life
import (
"sync"
)
// Life handles the creation of the background thread and shutdown management
type Life struct {
wg *sync.WaitGroup
Done chan struct{}
run func()
once *sync.Once
close *sync.Once
}
// NewLife creates life with the expected defaults
func NewLife() *Life {
return &Life{
wg: &sync.WaitGroup{},
Done: make(chan struct{}, 0),
once: &sync.Once{},
close: &sync.Once{},
}
}
// Start the background thread.
func (l Life) Start() {
l.once.Do(func() {
l.WGAdd(1)
go l.runner()
})
}
func (l Life) runner() {
defer l.wg.Done()
l.run()
}
// SetRun will set the run function that will be called by Start.
func (l *Life) SetRun(f func()) {
l.run = f
}
// WGAdd will add to life's waitgroup.
func (l Life) WGAdd(i int) {
l.wg.Add(i)
}
// WGDone will decrement life's waitgroup.
func (l Life) WGDone() {
l.wg.Done()
}
// Close will wait for the background thread to finish and then exit
func (l Life) Close() error {
l.close.Do(func() {
close(l.Done)
})
l.wg.Wait()
return nil
}