go-zero/core/threading/routinegroup.go

43 lines
965 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package threading
import "sync"
// A RoutineGroup is used to group goroutines together and all wait all goroutines to be done.
2020-07-26 17:09:05 +08:00
type RoutineGroup struct {
waitGroup sync.WaitGroup
}
// NewRoutineGroup returns a RoutineGroup.
2020-07-26 17:09:05 +08:00
func NewRoutineGroup() *RoutineGroup {
return new(RoutineGroup)
}
2021-02-09 13:50:21 +08:00
// Run runs the given fn in RoutineGroup.
2020-07-26 17:09:05 +08:00
// 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()
}()
}
2021-02-09 13:50:21 +08:00
// RunSafe runs the given fn in RoutineGroup, and avoid panics.
2020-07-26 17:09:05 +08:00
// 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()
})
}
2021-02-09 13:50:21 +08:00
// Wait waits all running functions to be done.
2020-07-26 17:09:05 +08:00
func (g *RoutineGroup) Wait() {
g.waitGroup.Wait()
}