routinegroup.go 827 B

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