-
Notifications
You must be signed in to change notification settings - Fork 4
/
waitgroup.go
64 lines (56 loc) · 1.25 KB
/
waitgroup.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
package waitgroup
import (
"sync"
)
// WaitGroup implements a simple goruntine pool.
type WaitGroup struct {
size int
pool chan byte
waitCount int64
waitGroup sync.WaitGroup
}
// NewWaitGroup creates a waitgroup with a specific size (the maximum number of
// goroutines to run at the same time). If you use -1 as the size, all items
// will run concurrently (just like a normal sync.WaitGroup)
func NewWaitGroup(size int) *WaitGroup {
wg := &WaitGroup{
size: size,
}
if size > 0 {
wg.pool = make(chan byte, size)
}
return wg
}
// Add add the function close to the waitgroup
func (wg *WaitGroup) Add(closures ...func()) {
for _, c := range closures {
closure := c
wg.BlockAdd()
go func() {
defer wg.Done()
closure()
}()
}
}
// BlockAdd pushes ‘one’ into the group. Blocks if the group is full.
func (wg *WaitGroup) BlockAdd() {
if wg.size > 0 {
wg.pool <- 1
}
wg.waitGroup.Add(1)
}
// Done pops ‘one’ out the group.
func (wg *WaitGroup) Done() {
if wg.size > 0 {
<-wg.pool
}
wg.waitGroup.Done()
}
// Wait waiting the group empty
func (wg *WaitGroup) Wait() {
wg.waitGroup.Wait()
}
// PendingCount returns the number of pending operations
func (wg *WaitGroup) PendingCount() int64 {
return int64(len(wg.pool))
}