You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/threading/routinegroup.go

41 lines
827 B
Go

package threading
import "sync"
type RoutineGroup struct {
waitGroup sync.WaitGroup
}
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()
}