github.com/lingyao2333/mo-zero@v1.4.1/core/threading/routinegroup.go (about)

     1  package threading
     2  
     3  import "sync"
     4  
     5  // A RoutineGroup is used to group goroutines together and all wait all goroutines to be done.
     6  type RoutineGroup struct {
     7  	waitGroup sync.WaitGroup
     8  }
     9  
    10  // NewRoutineGroup returns a RoutineGroup.
    11  func NewRoutineGroup() *RoutineGroup {
    12  	return new(RoutineGroup)
    13  }
    14  
    15  // Run runs the given fn in RoutineGroup.
    16  // Don't reference the variables from outside,
    17  // because outside variables can be changed by other goroutines
    18  func (g *RoutineGroup) Run(fn func()) {
    19  	g.waitGroup.Add(1)
    20  
    21  	go func() {
    22  		defer g.waitGroup.Done()
    23  		fn()
    24  	}()
    25  }
    26  
    27  // RunSafe runs the given fn in RoutineGroup, and avoid panics.
    28  // Don't reference the variables from outside,
    29  // because outside variables can be changed by other goroutines
    30  func (g *RoutineGroup) RunSafe(fn func()) {
    31  	g.waitGroup.Add(1)
    32  
    33  	GoSafe(func() {
    34  		defer g.waitGroup.Done()
    35  		fn()
    36  	})
    37  }
    38  
    39  // Wait waits all running functions to be done.
    40  func (g *RoutineGroup) Wait() {
    41  	g.waitGroup.Wait()
    42  }