You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

39 lines
759 B

  1. package multierror
  2. import "sync"
  3. // Group is a collection of goroutines which return errors that need to be
  4. // coalesced.
  5. type Group struct {
  6. mutex sync.Mutex
  7. err *Error
  8. wg sync.WaitGroup
  9. }
  10. // Go calls the given function in a new goroutine.
  11. //
  12. // If the function returns an error it is added to the group multierror which
  13. // is returned by Wait.
  14. func (g *Group) Go(f func() error) {
  15. g.wg.Add(1)
  16. go func() {
  17. defer g.wg.Done()
  18. if err := f(); err != nil {
  19. g.mutex.Lock()
  20. g.err = Append(g.err, err)
  21. g.mutex.Unlock()
  22. }
  23. }()
  24. }
  25. // Wait blocks until all function calls from the Go method have returned, then
  26. // returns the multierror.
  27. func (g *Group) Wait() *Error {
  28. g.wg.Wait()
  29. g.mutex.Lock()
  30. defer g.mutex.Unlock()
  31. return g.err
  32. }