-
Notifications
You must be signed in to change notification settings - Fork 0
/
signalwait.go
78 lines (61 loc) · 1.15 KB
/
signalwait.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
package beater
import (
"sync"
"time"
"github.com/elastic/beats/libbeat/logp"
)
type signalWait struct {
count int // number of potential 'alive' signals
signals chan struct{}
}
type signaler func()
func newSignalWait() *signalWait {
return &signalWait{
signals: make(chan struct{}, 1),
}
}
func (s *signalWait) Wait() {
if s.count == 0 {
return
}
<-s.signals
s.count--
}
func (s *signalWait) Add(fn signaler) {
s.count++
go func() {
fn()
var v struct{}
s.signals <- v
}()
}
func (s *signalWait) AddChan(c <-chan struct{}) {
s.Add(waitChannel(c))
}
func (s *signalWait) AddTimer(t *time.Timer) {
s.Add(waitTimer(t))
}
func (s *signalWait) AddTimeout(d time.Duration) {
s.Add(waitDuration(d))
}
func (s *signalWait) Signal() {
s.Add(func() {})
}
func waitGroup(wg *sync.WaitGroup) signaler {
return wg.Wait
}
func waitChannel(c <-chan struct{}) signaler {
return func() { <-c }
}
func waitTimer(t *time.Timer) signaler {
return func() { <-t.C }
}
func waitDuration(d time.Duration) signaler {
return waitTimer(time.NewTimer(d))
}
func withLog(s signaler, msg string) signaler {
return func() {
s()
logp.Info("%v", msg)
}
}