Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wait with context to avoid blocking #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions sizedwaitgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,20 @@ func (s *SizedWaitGroup) Done() {
func (s *SizedWaitGroup) Wait() {
s.wg.Wait()
}

// Wait blocks until the SizedWaitGroup counter is zero or the context is Done.
// See sync.WaitGroup documentation for more information.
func (s *SizedWaitGroup) WaitWithContext(ctx context.Context) error {
done := make(chan struct{})
go func() {
defer close(done)
s.Wait()
done <- struct{}{}
}()
Comment on lines +90 to +94
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this will leak goroutine each time WaitWithContext is called w/ an expired context until wg finishes.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could document it as such? Given a context that has been cancelled, via os.Interrupt for example, I thought it better to orphan the goroutine and have the application exit when graceful immediate shutdown of all the goroutines in the sizedWaitGroup is not possible.

select {
case <-ctx.Done():
return ctx.Err()
case <-done:
}
return nil
}
23 changes: 23 additions & 0 deletions sizedwaitgroup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,26 @@ func TestAddWithContext(t *testing.T) {
}

}

func TestWaitWithContext(t *testing.T) {
t.Run("cancelled context error is returned", func(t *testing.T) {
ctx, cancelFunc := context.WithCancel(context.TODO())

swg := New(1)
swg.Add()
cancelFunc()

if err := swg.WaitWithContext(ctx); err != context.Canceled {
t.Fatalf("expected cancelled context: %s", err)
}
})
t.Run("done group returns nil", func(t *testing.T) {
swg := New(1)
swg.Add()
swg.Done()

if err := swg.WaitWithContext(context.TODO()); err != nil {
t.Fatalf("expected nil: %s", err)
}
})
}