Skip to content

Commit

Permalink
opt: leverage binary-search algorithm to speed up PoolWithFunc.purgeS…
Browse files Browse the repository at this point in the history
…taleWorkers()
  • Loading branch information
panjf2000 committed Dec 11, 2022
1 parent 7b1e246 commit 3fbd956
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Expand Up @@ -40,7 +40,7 @@ jobs:
uses: golangci/golangci-lint-action@v3
with:
version: v1.50.1
args: -v -E gofumpt -E gocritic -E misspell -E revive -E godot
args: --timeout 5m -v -E gofumpt -E gocritic -E misspell -E revive -E godot
test:
needs: lint
strategy:
Expand Down
16 changes: 12 additions & 4 deletions pool_func.go
Expand Up @@ -89,17 +89,25 @@ func (p *PoolWithFunc) purgeStaleWorkers(ctx context.Context) {
break
}

currentTime := time.Now()
criticalTime := time.Now().Add(-p.options.ExpiryDuration)

p.lock.Lock()
idleWorkers := p.workers
n := len(idleWorkers)
var i int
for i = 0; i < n && currentTime.Sub(idleWorkers[i].recycleTime) > p.options.ExpiryDuration; i++ {
l, r, mid := 0, n-1, 0
for l <= r {
mid = (l + r) / 2
if criticalTime.Before(idleWorkers[mid].recycleTime) {
r = mid - 1
} else {
l = mid + 1
}
}
i := r + 1
expiredWorkers = append(expiredWorkers[:0], idleWorkers[:i]...)
if i > 0 {
m := copy(idleWorkers, idleWorkers[i:])
for i = m; i < n; i++ {
for i := m; i < n; i++ {
idleWorkers[i] = nil
}
p.workers = idleWorkers[:m]
Expand Down

0 comments on commit 3fbd956

Please sign in to comment.