-
Notifications
You must be signed in to change notification settings - Fork 1
/
wait-group.go
76 lines (62 loc) · 1.37 KB
/
wait-group.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
/*
© 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parl
import (
"fmt"
"sync"
)
// parl.WaitGroup is like a sync.Waitgroup that can be inspected.
// The Waiting method returns the number of threads waited for.
// parl.WaitGroup requires no initialization.
//
// var wg parl.WaitGroup
// wg.Add(1)
// …
// wg.Waiting()
type WaitGroup struct {
sync.WaitGroup // Wait()
lock sync.Mutex
adds int
dones int
}
func NewWaitGroup() (waitGroup *WaitGroup) {
return &WaitGroup{}
}
func (wg *WaitGroup) Add(delta int) {
wg.lock.Lock()
defer wg.lock.Unlock()
wg.adds += delta
wg.WaitGroup.Add(delta)
}
func (wg *WaitGroup) Done() {
wg.DoneBool()
}
func (wg *WaitGroup) DoneBool() (isExit bool) {
wg.lock.Lock()
defer wg.lock.Unlock()
wg.dones++
wg.WaitGroup.Done()
return wg.dones == wg.adds
}
func (wg *WaitGroup) Count() (remaining int) {
adds, dones := wg.Counters()
remaining = adds - dones
return
}
func (wg *WaitGroup) Counters() (adds int, dones int) {
wg.lock.Lock()
defer wg.lock.Unlock()
adds = wg.adds
dones = wg.dones
return
}
func (wg *WaitGroup) IsZero() (isZero bool) {
adds, dones := wg.Counters()
return adds == dones
}
func (wg *WaitGroup) String() (s string) {
adds, dones := wg.Counters()
return fmt.Sprintf("%d(%d)", adds-dones, adds)
}