Skip to content

Commit

Permalink
PR feedback on job order and ctx.Err check
Browse files Browse the repository at this point in the history
Signed-off-by: Oleg Zaytsev <[email protected]>
  • Loading branch information
colega committed Jan 11, 2022
1 parent 6faae52 commit bae0d79
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions concurrency/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,23 +89,23 @@ func ForEachJob(ctx context.Context, jobs int, concurrency int, jobFunc func(ctx
return nil
}

indexes := atomic.Int64{}
indexes.Add(int64(jobs))
// Initialise indexes with -1 so first Inc() returns index 0.
indexes := atomic.NewInt64(-1)

// Start workers to process jobs.
g, ctx := errgroup.WithContext(ctx)
for ix := 0; ix < math.Min(concurrency, jobs); ix++ {
g.Go(func() error {
for {
idx := int(indexes.Dec())
if idx < 0 {
return nil
}

if err := ctx.Err(); err != nil {
return err
}

idx := int(indexes.Inc())
if idx >= jobs {
return nil
}

if err := jobFunc(ctx, idx); err != nil {
return err
}
Expand Down

0 comments on commit bae0d79

Please sign in to comment.