From 798a61d1752e6d7f3482c3fbe9640eede5e64571 Mon Sep 17 00:00:00 2001 From: Andy Pan Date: Sun, 20 May 2018 03:35:31 +0800 Subject: [PATCH] optimize memory using --- ants.go | 2 +- ants_benchmark_test.go | 2 +- pool.go | 33 +++++++++++++++++++++++++-------- worker.go | 16 ---------------- 4 files changed, 27 insertions(+), 26 deletions(-) diff --git a/ants.go b/ants.go index 7c51439..5f1166c 100644 --- a/ants.go +++ b/ants.go @@ -1,6 +1,6 @@ package ants -const DEFAULT_POOL_SIZE = 50000 +const DEFAULT_POOL_SIZE = 5 var defaultPool = NewPool(DEFAULT_POOL_SIZE) diff --git a/ants_benchmark_test.go b/ants_benchmark_test.go index 8246a32..029c768 100644 --- a/ants_benchmark_test.go +++ b/ants_benchmark_test.go @@ -6,7 +6,7 @@ import ( "sync" ) -const RunTimes = 10000 +const RunTimes = 100000 func BenchmarkPoolGroutine(b *testing.B) { for i := 0; i < b.N; i++ { diff --git a/pool.go b/pool.go index 50e4a09..b53afbf 100644 --- a/pool.go +++ b/pool.go @@ -76,24 +76,41 @@ func (p *Pool) reachLimit() bool { } func (p *Pool) newWorker() *Worker { + var w *Worker if p.reachLimit() { <-p.freeSignal return p.getWorker() } - worker := &Worker{ - pool: p, - task: make(chan f), + wp := p.workerPool.Get() + if wp == nil { + w = &Worker{ + pool: p, + task: make(chan f), + } + } else { + w = wp.(*Worker) } - worker.run() + w.run() atomic.AddInt32(&p.running, 1) - return worker + return w } func (p *Pool) getWorker() *Worker { - if w := p.workerPool.Get(); w != nil { - return w.(*Worker) + var w *Worker + p.m.Lock() + workers := p.workers + n := len(workers) - 1 + if n < 0 { + p.m.Unlock() + return p.newWorker() + } else { + w = workers[n] + workers[n] = nil + p.workers = workers[:n] + atomic.AddInt32(&p.running, 1) } - return p.newWorker() + p.m.Unlock() + return w } func (p *Pool) putWorker(worker *Worker) { diff --git a/worker.go b/worker.go index 1cd5949..ed13b39 100644 --- a/worker.go +++ b/worker.go @@ -9,22 +9,6 @@ type Worker struct { task chan f } -//func (w *Worker) run() { -// go func() { -// for { -// select { -// case f := <-w.task: -// f() -// w.pool.putWorker(w) -// w.pool.wg.Done() -// case <-w.exit: -// atomic.AddInt32(&w.pool.running, -1) -// return -// } -// } -// }() -//} - func (w *Worker) run() { go func() { for f := range w.task {