-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwg.go
58 lines (48 loc) · 1.12 KB
/
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package safewrapper
import (
"sync"
)
// WaitGroup wrap sync.WaitGroup
// Compatible with the go library's waitGroup operations
type WaitGroup struct {
wg sync.WaitGroup
}
// Wrap fn func in goroutine to run,It's relatively unsafe.
// Note: panic is not caught here, because we know for sure that panic will not be thrown,
// so we don't need to catch processing
func (w *WaitGroup) Wrap(fn func()) {
w.wg.Add(1)
go func() {
defer w.wg.Done()
fn()
}()
}
// WrapWithRecover exec func with recover safely
func (w *WaitGroup) WrapWithRecover(fn func(), recoveryFunc ...func(r interface{})) {
var recoveryHandler = defaultRecoveryFunc
if len(recoveryFunc) > 0 && recoveryFunc[0] != nil {
recoveryHandler = recoveryFunc[0]
}
w.wg.Add(1)
go func() {
defer func() {
if r := recover(); r != nil {
recoveryHandler(r)
}
}()
defer w.wg.Done()
fn()
}()
}
// Wait this func wait for a set of goroutines to complete execution
func (w *WaitGroup) Wait() {
w.wg.Wait()
}
// Done wg delta counter minus 1
func (w *WaitGroup) Done() {
w.wg.Done()
}
// Add delta+1
func (w *WaitGroup) Add(delta int) {
w.wg.Add(delta)
}