forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routinegroup.go
42 lines (34 loc) · 965 Bytes
/
routinegroup.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
package threading
import "sync"
// A RoutineGroup is used to group goroutines together and all wait all goroutines to be done.
type RoutineGroup struct {
waitGroup sync.WaitGroup
}
// NewRoutineGroup returns a RoutineGroup.
func NewRoutineGroup() *RoutineGroup {
return new(RoutineGroup)
}
// Run runs the given fn in RoutineGroup.
// Don't reference the variables from outside,
// because outside variables can be changed by other goroutines
func (g *RoutineGroup) Run(fn func()) {
g.waitGroup.Add(1)
go func() {
defer g.waitGroup.Done()
fn()
}()
}
// RunSafe runs the given fn in RoutineGroup, and avoid panics.
// Don't reference the variables from outside,
// because outside variables can be changed by other goroutines
func (g *RoutineGroup) RunSafe(fn func()) {
g.waitGroup.Add(1)
GoSafe(func() {
defer g.waitGroup.Done()
fn()
})
}
// Wait waits all running functions to be done.
func (g *RoutineGroup) Wait() {
g.waitGroup.Wait()
}