mirror of https://github.com/panjf2000/ants.git
优化清理速度并修复内存泄漏
This commit is contained in:
parent
fc48d32604
commit
21a109c7f0
31
pool.go
31
pool.go
|
@ -68,6 +68,7 @@ func (p *Pool) periodicallyPurge() {
|
||||||
heartbeat := time.NewTicker(p.expiryDuration)
|
heartbeat := time.NewTicker(p.expiryDuration)
|
||||||
defer heartbeat.Stop()
|
defer heartbeat.Stop()
|
||||||
|
|
||||||
|
var purgeWorkers []*Worker
|
||||||
for range heartbeat.C {
|
for range heartbeat.C {
|
||||||
if CLOSED == atomic.LoadInt32(&p.release) {
|
if CLOSED == atomic.LoadInt32(&p.release) {
|
||||||
break
|
break
|
||||||
|
@ -75,23 +76,29 @@ func (p *Pool) periodicallyPurge() {
|
||||||
currentTime := time.Now()
|
currentTime := time.Now()
|
||||||
p.lock.Lock()
|
p.lock.Lock()
|
||||||
idleWorkers := p.workers
|
idleWorkers := p.workers
|
||||||
n := -1
|
n := len(idleWorkers)
|
||||||
for i, w := range idleWorkers {
|
i := 0
|
||||||
if currentTime.Sub(w.recycleTime) <= p.expiryDuration {
|
for i < n && currentTime.Sub(idleWorkers[i].recycleTime) > p.expiryDuration {
|
||||||
break
|
i++
|
||||||
}
|
}
|
||||||
n = i
|
purgeWorkers = append(purgeWorkers[:0], idleWorkers[:i]...)
|
||||||
w.task <- nil
|
if i > 0 {
|
||||||
|
m := copy(idleWorkers, idleWorkers[i:])
|
||||||
|
for i = m; i < n; i++ {
|
||||||
idleWorkers[i] = nil
|
idleWorkers[i] = nil
|
||||||
}
|
}
|
||||||
if n > -1 {
|
p.workers = idleWorkers[:m]
|
||||||
if n >= len(idleWorkers)-1 {
|
|
||||||
p.workers = idleWorkers[:0]
|
|
||||||
} else {
|
|
||||||
p.workers = idleWorkers[n+1:]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
p.lock.Unlock()
|
p.lock.Unlock()
|
||||||
|
|
||||||
|
// Notify obsolete workers to stop.
|
||||||
|
// This notification must be outside the p.lock, since w.task
|
||||||
|
// may be blocking and may consume a lot of time if many workers
|
||||||
|
// are located on non-local CPUs.
|
||||||
|
for i, w := range purgeWorkers {
|
||||||
|
w.task <- nil
|
||||||
|
purgeWorkers[i] = nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue