Skip to content

Commit

Permalink
always cancel executors' contexts
Browse files Browse the repository at this point in the history
  • Loading branch information
mumbleskates committed Sep 23, 2024
1 parent 1d7e087 commit 467247c
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions group.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,11 @@ func Unlimited(ctx context.Context) Executor {
func Limited(ctx context.Context, maxGoroutines int) Executor {
if maxGoroutines < 1 {
gctx, cancel := context.WithCancelCause(ctx)
return &runner{ctx: gctx, cancel: cancel}
g := &runner{ctx: gctx, cancel: cancel}
runtime.SetFinalizer(g, func(doomed *runner) {
doomed.cancel(nil)
})
return g
}
making := &limitedGroup{
g: makeGroup(context.WithCancelCause(ctx)),
Expand Down Expand Up @@ -96,14 +100,22 @@ func (n *runner) Go(op func(context.Context)) {

func (n *runner) Wait() {
n.awaited.Store(true)
// We are ending the group's lifetime within this function call; defer the
// cancelation and unset our finalizer.
n.cancel(nil)
runtime.SetFinalizer(n, nil)
}

func (n *runner) getContext() (context.Context, context.CancelCauseFunc) {
return n.ctx, n.cancel
}

func makeGroup(ctx context.Context, cancel context.CancelCauseFunc) *group {
return &group{runner: runner{ctx: ctx, cancel: cancel}}
g := &group{runner: runner{ctx: ctx, cancel: cancel}}
runtime.SetFinalizer(g, func(doomed *group) {
doomed.cancel(nil)
})
return g
}

// Base concurrent executor
Expand Down Expand Up @@ -147,6 +159,10 @@ func (g *group) Go(op func(context.Context)) {

func (g *group) Wait() {
g.awaited.Store(true)
// We are ending the group's lifetime within this function call; defer the
// cancelation and unset our finalizer.
defer g.cancel(nil)
runtime.SetFinalizer(g, nil)
g.wg.Wait()
g.checkPanic()
}
Expand Down

0 comments on commit 467247c

Please sign in to comment.