-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecgroup.go
More file actions
60 lines (54 loc) · 1.02 KB
/
execgroup.go
File metadata and controls
60 lines (54 loc) · 1.02 KB
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
package execgroup
import (
"errors"
"fmt"
"sync"
)
// ExecGroup uses a WaitGroup to allow multiple functions to be called
// concurrently.
type ExecGroup struct {
wg sync.WaitGroup
me MultiError
m sync.Mutex
}
// Do executes the provided function in a goroutine.
func (e *ExecGroup) Do(fn func()) {
e.wg.Add(1)
go func() {
defer func() {
if r := recover(); r != nil {
if err, ok := r.(error); ok {
e.TrackError(err)
} else {
msg := fmt.Sprintf("panic in execgroup: %s", r)
e.TrackError(errors.New(msg))
}
}
e.wg.Done()
}()
fn()
}()
}
// TrackError tracks an error that occurred.
func (e *ExecGroup) TrackError(err error) {
if err != nil {
e.m.Lock()
defer e.m.Unlock()
e.me = e.me.Append(err)
}
}
// Wait for all functions to complete.
func (e *ExecGroup) Wait() error {
e.wg.Wait()
if len(e.me) == 0 {
return nil
}
return e.me
}
// Error returns a MultiError if any errors occurred.
func (e *ExecGroup) Error() error {
if len(e.me) != 0 {
return e.me
}
return nil
}