-
Notifications
You must be signed in to change notification settings - Fork 129
Description
Can you help explain how to properly use WithWaitGroup() especially when an error occurs? I seem to be having some misunderstanding.
The general pattern without using a progress bar which works is:
- create a
wg sync.WaitGroupand for each loop callwg.Add(1) - for each loop create a
go funcwithdefer wg.Done()that calls aDoWorkfunction which internally callsbar.Increment() - call
wg.Wait()and collect any errors
To use the mpb library I used mpb.New(mpb.WithWaitGroup(&wg)) and called progressBar.Wait() instead of wg.Wait(). See below code. However, if the DoWork() errors such as before bar.Increment() is called the progressBar.Wait() never returns. Adding a bar.Abort() when an error occurs seems to work, but is a pattern that seems incorrect and one I'd like to avoid.
Note: I have also tried the below code without a WaitGroup and just progressBar := mpb.New() and it still hangs on progressBar.Wait() unless I add a bar.Abort() if an error is returned from DoWork, which does not seem correct.
I am not sure I understand the point of WithWaitGroup if the below code works the same without needing it. Can you explain?
Thank you for any clarification and help in understanding!
var wg sync.WaitGroup
progressBar := mpb.New(mpb.WithWaitGroup(&wg))
errChan := make(chan error, len(databases))
for _, database := range databases {
wg.Add(1)
bar := progressBar.New(int64(database.NumScriptsToDoWork),
mpb.NopStyle(),
mpb.PrependDecorators(decor.Name(database.Datname, decor.WCSyncSpaceR)),
mpb.AppendDecorators(decor.NewPercentage()),
)
go func(database DatabaseInfo, bar *mpb.Bar) {
defer wg.Done()
err = DoWork(database, bar) // calls bar.Increment()
if err != nil {
errChan <- err
return
}
}(database, bar)
}
progressBar.Wait()
close(errChan)
// ...