-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwg.go
44 lines (38 loc) · 959 Bytes
/
wg.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
package cloudping
import (
"sync"
)
// A WaitGroupLimit waits for a collection of goroutines to finish.
// It's wrapper around the waitgroup struct to add concurrency limit.
type WaitGroupLimit struct {
ch chan int
wg *sync.WaitGroup
}
// NewWaitGroupLimit creates a new runner for concurrency tasks
func NewWaitGroupLimit(limit int) *WaitGroupLimit {
if limit <= 0 {
limit = 1
}
return &WaitGroupLimit{
ch: make(chan int, limit), // buffer chan to limit concurrency
wg: &sync.WaitGroup{},
}
}
// Add adds delta, which may be negative, to the WaitGroup counter.
// See sync.WaitGroup for more info.
func (wgl *WaitGroupLimit) Add(delta int) {
for i := 0; i < delta; i++ {
wgl.ch <- 1
wgl.wg.Add(1)
}
}
// Done decrements the WaitGroup counter by one.
func (wgl *WaitGroupLimit) Done() {
wgl.wg.Done()
<-wgl.ch
}
// Wait blocks until the WaitGroup counter is zero.
func (wgl *WaitGroupLimit) Wait() {
close(wgl.ch)
wgl.wg.Wait()
}