github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zsync/waitgroup.go (about) 1 package zsync 2 3 import ( 4 "sync" 5 6 "github.com/sohaha/zlsgo/zerror" 7 ) 8 9 type WaitGroup struct { 10 err error 11 wg sync.WaitGroup 12 mu sync.RWMutex 13 } 14 15 func (h *WaitGroup) Add(delta int) { 16 h.wg.Add(delta) 17 } 18 19 func (h *WaitGroup) Done() { 20 h.wg.Done() 21 } 22 23 func (h *WaitGroup) Go(f func()) { 24 h.Add(1) 25 go func() { 26 defer h.Done() 27 f() 28 }() 29 } 30 31 func (h *WaitGroup) GoTry(f func()) { 32 h.Add(1) 33 go func() { 34 defer h.Done() 35 err := zerror.TryCatch(func() error { 36 f() 37 return nil 38 }) 39 40 if err != nil { 41 h.mu.Lock() 42 if h.err == nil { 43 h.err = err 44 } 45 h.mu.Unlock() 46 } 47 }() 48 } 49 50 func (h *WaitGroup) Wait() error { 51 h.wg.Wait() 52 return h.err 53 }