routinegroup.go 673 B

12345678910111213141516171819202122232425262728293031323334353637
  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. // Don't reference the variables from outside,
  10. // because outside variables can be changed by other goroutines
  11. func (g *RoutineGroup) Run(fn func()) {
  12. g.waitGroup.Add(1)
  13. go func() {
  14. defer g.waitGroup.Done()
  15. fn()
  16. }()
  17. }
  18. // Don't reference the variables from outside,
  19. // because outside variables can be changed by other goroutines
  20. func (g *RoutineGroup) RunSafe(fn func()) {
  21. g.waitGroup.Add(1)
  22. GoSafe(func() {
  23. defer g.waitGroup.Done()
  24. fn()
  25. })
  26. }
  27. func (g *RoutineGroup) Wait() {
  28. g.waitGroup.Wait()
  29. }