-
Notifications
You must be signed in to change notification settings - Fork 1
/
wg-waiter.go
67 lines (55 loc) · 1 KB
/
wg-waiter.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
package wgwaiter
import (
"sync"
"time"
)
type WgWaiter struct {
wg sync.WaitGroup
errChannel chan error
finished chan bool
mux sync.Mutex
}
func NewWaiter() *WgWaiter {
return &WgWaiter{
wg: sync.WaitGroup{},
errChannel: make(chan error),
finished: make(chan bool, 1),
}
}
func (wg *WgWaiter) AddOne() {
wg.wg.Add(1)
}
func (wg *WgWaiter) Add(delta int) {
wg.wg.Add(delta)
}
func (wg *WgWaiter) Done() {
wg.wg.Done()
}
func (wg *WgWaiter) Fail(err error) {
wg.errChannel <- err
wg.wg.Done()
}
func (wg *WgWaiter) Lock() {
wg.mux.Lock()
}
func (wg *WgWaiter) Unlock() {
wg.mux.Unlock()
}
func (wg *WgWaiter) Wait(timeout time.Duration) error {
go func() {
wg.wg.Wait()
wg.finished <- true
}()
select {
case err := <-wg.errChannel:
return err
case <-wg.finished:
return nil
case <-time.After(timeout):
return TimeoutError(timeout.String())
}
}
type TimeoutError string
func (te TimeoutError) Error() string {
return "Timeout after " + string(te)
}