github.com/camlistore/go4@v0.0.0-20200104003542-c7e774b10ea0/syncutil/group.go (about) 1 /* 2 Copyright 2013 Google Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package syncutil 18 19 import "sync" 20 21 // A Group is like a sync.WaitGroup and coordinates doing 22 // multiple things at once. Its zero value is ready to use. 23 type Group struct { 24 wg sync.WaitGroup 25 mu sync.Mutex // guards errs 26 errs []error 27 } 28 29 // Go runs fn in its own goroutine, but does not wait for it to complete. 30 // Call Err or Errs to wait for all the goroutines to complete. 31 func (g *Group) Go(fn func() error) { 32 g.wg.Add(1) 33 go func() { 34 defer g.wg.Done() 35 err := fn() 36 if err != nil { 37 g.mu.Lock() 38 defer g.mu.Unlock() 39 g.errs = append(g.errs, err) 40 } 41 }() 42 } 43 44 // Wait waits for all the previous calls to Go to complete. 45 func (g *Group) Wait() { 46 g.wg.Wait() 47 } 48 49 // Err waits for all previous calls to Go to complete and returns the 50 // first non-nil error, or nil. 51 func (g *Group) Err() error { 52 g.wg.Wait() 53 if len(g.errs) > 0 { 54 return g.errs[0] 55 } 56 return nil 57 } 58 59 // Errs waits for all previous calls to Go to complete and returns 60 // all non-nil errors. 61 func (g *Group) Errs() []error { 62 g.wg.Wait() 63 return g.errs 64 }