Skip to content

WithWaitGroup hangs on error. Help explain how to use WithWaitGroup. #130

@kalensk

Description

@kalensk

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.WaitGroup and for each loop call wg.Add(1)
  • for each loop create a go func with defer wg.Done() that calls a DoWork function which internally calls bar.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)

// ...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions