Skip to content

Commit

Permalink
feat:avoid too many goroutines by ants pool
Browse files Browse the repository at this point in the history
Signed-off-by: FanOne <[email protected]>
  • Loading branch information
CocaineCong committed Jun 11, 2024
1 parent 80a2cd1 commit 3951e85
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions pkg/util/distance/calc_distance.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"sync"

"github.com/cockroachdb/errors"
"github.com/panjf2000/ants/v2"
)

/**
Expand Down Expand Up @@ -130,15 +131,27 @@ func CalcFloatDistance(dim int64, left, right []float32, metric string) ([]float

distArray := make([]float32, leftNum*rightNum)

// Multi-threads to calculate distance. TODO: avoid too many go routines
// Multi-threads to calculate distance.
var waitGroup sync.WaitGroup
CalcWorker := func(index int64) {
CalcFFBatch(dim, left, index, right, metricUpper, &distArray)
calcWorker := func(index interface{}) {
i := index.(int64)
CalcFFBatch(dim, left, i, right, metricUpper, &distArray)
waitGroup.Done()
}
// avoid too many goroutines by ants pool
poolSize := int(leftNum / 3)
pool, err := ants.NewPoolWithFunc(poolSize, calcWorker)
if err != nil {
return nil, err
}
defer pool.Release()

for i := int64(0); i < leftNum; i++ {
waitGroup.Add(1)
go CalcWorker(i)
err = pool.Invoke(i)
if err != nil {
return nil, err
}
}
waitGroup.Wait()

Expand Down

0 comments on commit 3951e85

Please sign in to comment.