-
Notifications
You must be signed in to change notification settings - Fork 1
/
wait-group.go
86 lines (70 loc) · 1.51 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
77
78
79
80
81
82
83
84
85
86
/*
© 2021–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
ISC License
*/
package parl
import (
"fmt"
"sync"
"github.com/haraldrudell/parl/perrors"
)
/*
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 InitWaitGroup(wgp *WaitGroup) {
if wgp == nil {
panic(perrors.NewPF("wgp cannot be nil"))
}
wgp.WaitGroup = sync.WaitGroup{}
wgp.lock = sync.Mutex{}
wgp.adds = 0
wgp.dones = 0
}
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)
}