-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwaitgroup.go
64 lines (52 loc) · 1.11 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 goroutine pool.
type WaitGroup struct {
size int
pool chan byte
waitGroup sync.WaitGroup
}
// New creates a waitgroup with a specific size (the maxium number of
// goroutines to run at the same time). If you use -1 as the size, all items
// will run concurrentlu (just like a normal sync.WaitGroup).
func New(size int) *WaitGroup {
wg := &WaitGroup{
size: size,
}
if size > 0 {
wg.pool = make(chan byte, size)
}
return wg
}
// Add adds the function to the waitgroup.
func (wg *WaitGroup) Add(fns ...func()) {
for _, f := range fns {
fn := f
wg.blockAdd()
go func() {
defer wg.Done()
fn()
}()
}
}
func (wg *WaitGroup) blockAdd() {
if wg.size > 0 {
wg.pool <- 1
}
wg.waitGroup.Add(1)
}
// Done pops one out of the pool.
func (wg *WaitGroup) Done() {
if wg.size > 0 {
<-wg.pool
}
wg.waitGroup.Done()
}
// Wait waits the pool empty.
func (wg *WaitGroup) Wait() {
wg.waitGroup.Wait()
}
// PendingCount returns the number of pending tasks.
func (wg *WaitGroup) PendingCount() int64 {
return int64(len(wg.pool))
}