Skip to content

Commit

Permalink
indices: fix race condition in ProcessSlice
Browse files Browse the repository at this point in the history
  • Loading branch information
adamdecaf committed Jan 14, 2025
1 parent 2582e79 commit 2c54d75
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions internal/indices/indices.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,28 @@ func New(total, groups int) []int {

// ProcessSlice processes input slice concurrently using the provided function
func ProcessSlice[T any, F any](in []T, groups int, f func(T) F) []F {
out := make([]F, 0, len(in)) // set capacity on creation
ProcessSliceFn[T](in, groups, func(v T) {
out = append(out, f(v))
})
results := make(chan F, len(in))

var wg sync.WaitGroup
wg.Add(len(in))

for _, elm := range in {
go func(v T) {
defer wg.Done()
results <- f(v)
}(elm)
}

go func() {
wg.Wait()
close(results)
}()

out := make([]F, 0, len(in))
for result := range results {
out = append(out, result)
}

return out
}

Expand Down

0 comments on commit 2c54d75

Please sign in to comment.