routinegroup.go 965 B

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