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

Synchronize read & write of TaskGroupWithContext's err variable #37

Merged
merged 1 commit into from
Oct 14, 2022
Merged
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
23 changes: 17 additions & 6 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,14 @@ func (g *TaskGroup) Wait() {
// TaskGroupWithContext represents a group of related tasks associated to a context
type TaskGroupWithContext struct {
TaskGroup
ctx context.Context
cancel context.CancelFunc
errOnce sync.Once
err error
ctx context.Context
cancel context.CancelFunc

errSync struct {
once sync.Once
guard sync.RWMutex
}
err error
}

// Submit adds a task to this group and sends it to the worker pool to be executed
Expand All @@ -57,8 +61,11 @@ func (g *TaskGroupWithContext) Submit(task func() error) {
// don't actually ignore errors
err := task()
if err != nil {
g.errOnce.Do(func() {
g.errSync.once.Do(func() {
g.errSync.guard.Lock()
g.err = err
g.errSync.guard.Unlock()

if g.cancel != nil {
g.cancel()
}
Expand Down Expand Up @@ -86,5 +93,9 @@ func (g *TaskGroupWithContext) Wait() error {
case <-g.ctx.Done():
}

Choose a reason for hiding this comment

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

You have to return g.ctx.Err(), otherwise we will get a data race.

ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()

g, gctx := pool.GroupContext(ctx)
g.Submit(func() error { select { case <-gctx.Done(): return gctx.Err() }})
err := g.Wait() // err == nil

Copy link
Owner

Choose a reason for hiding this comment

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

Oh, good catch @NOMORECOFFEE!. If you don't mind, please open a PR with suggested changes and I can review it later. Otherwise I can send one. Thank you! 🙌

Copy link
Owner

Choose a reason for hiding this comment

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

I just released v1.8.3 with a fix for this, please check it out and let me know if you find anything. Thank you!


return g.err
g.errSync.guard.RLock()
err := g.err
g.errSync.guard.RUnlock()

return err
}