forked from Angey40/BaiduPCS-Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait_group.go
48 lines (41 loc) · 940 Bytes
/
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
package pcsutil
import "sync"
// WaitGroup 在 sync.WaitGroup 的基础上, 新增线程控制功能
type WaitGroup struct {
wg sync.WaitGroup
p chan struct{}
}
// NewWaitGroup returns a pointer to a new `WaitGroup` object.
// parallel 为最大并发数, 0 代表无限制
func NewWaitGroup(parallel int) (w *WaitGroup) {
w = &WaitGroup{}
if parallel <= 0 {
return
}
w.p = make(chan struct{}, parallel)
return
}
// AddDelta 在 sync.WaitGroup 的基础上, 新增线程控制功能
func (w *WaitGroup) AddDelta() {
w.wg.Add(1)
if w.p == nil {
return
}
w.p <- struct{}{}
}
// Done 在 sync.WaitGroup 的基础上, 新增线程控制功能
func (w *WaitGroup) Done() {
w.wg.Done()
if w.p == nil {
return
}
<-w.p
}
// Wait 参照 sync.WaitGroup 的 Wait 方法
func (w *WaitGroup) Wait() {
w.wg.Wait()
}
// Parallel 返回当前正在进行的任务数量
func (w *WaitGroup) Parallel() int {
return len(w.p)
}