From ef6017217221e20416d886c0231dd5134752ef4e Mon Sep 17 00:00:00 2001 From: thinkgo <49174849+thinkgos@users.noreply.github.com> Date: Sat, 29 Aug 2020 18:51:56 +0800 Subject: [PATCH] Avoid memory leak (#107) --- pool.go | 1 + worker_loop_queue.go | 2 ++ worker_stack.go | 5 +++++ 3 files changed, 8 insertions(+) diff --git a/pool.go b/pool.go index 8b3946e..bf2c1e9 100644 --- a/pool.go +++ b/pool.go @@ -81,6 +81,7 @@ func (p *Pool) purgePeriodically() { // are located on non-local CPUs. for i := range expiredWorkers { expiredWorkers[i].task <- nil + expiredWorkers[i] = nil } // There might be a situation that all workers have been cleaned up(no any worker is running) diff --git a/worker_loop_queue.go b/worker_loop_queue.go index 3c15e55..2f4a79e 100644 --- a/worker_loop_queue.go +++ b/worker_loop_queue.go @@ -68,6 +68,7 @@ func (wq *loopQueue) detach() *goWorker { } w := wq.items[wq.head] + wq.items[wq.head] = nil wq.head++ if wq.head == wq.size { wq.head = 0 @@ -90,6 +91,7 @@ func (wq *loopQueue) retrieveExpiry(duration time.Duration) []*goWorker { break } wq.expiry = append(wq.expiry, wq.items[wq.head]) + wq.items[wq.head] = nil wq.head++ if wq.head == wq.size { wq.head = 0 diff --git a/worker_stack.go b/worker_stack.go index 6d74b43..f6c2f40 100644 --- a/worker_stack.go +++ b/worker_stack.go @@ -35,6 +35,7 @@ func (wq *workerStack) detach() *goWorker { } w := wq.items[l-1] + wq.items[l-1] = nil // avoid memory leaks wq.items = wq.items[:l-1] return w @@ -53,6 +54,9 @@ func (wq *workerStack) retrieveExpiry(duration time.Duration) []*goWorker { if index != -1 { wq.expiry = append(wq.expiry, wq.items[:index+1]...) m := copy(wq.items, wq.items[index+1:]) + for i := m; i < n; i++ { + wq.items[i] = nil + } wq.items = wq.items[:m] } return wq.expiry @@ -74,6 +78,7 @@ func (wq *workerStack) binarySearch(l, r int, expiryTime time.Time) int { func (wq *workerStack) reset() { for i := 0; i < wq.len(); i++ { wq.items[i].task <- nil + wq.items[i] = nil } wq.items = wq.items[:0] }