diff --git a/pool.go b/pool.go index a5b9a15..2def8d2 100644 --- a/pool.go +++ b/pool.go @@ -56,6 +56,8 @@ type Pool struct { once sync.Once + cachePool sync.Pool + // PanicHandler is used to handle panics from each worker goroutine. // if nil, panics will be thrown out again from worker goroutines. PanicHandler func(interface{}) @@ -185,7 +187,7 @@ func (p *Pool) decRunning() { // getWorker returns a available worker to run the tasks. func (p *Pool) getWorker() *Worker { var w *Worker - waiting := false + var waiting bool p.lock.Lock() defer p.lock.Unlock() @@ -193,7 +195,13 @@ func (p *Pool) getWorker() *Worker { idleWorkers := p.workers n := len(idleWorkers) - 1 if n < 0 { - waiting = p.Running() >= p.Cap() + if p.Running() >= p.Cap() { + waiting = true + } else { + if cacheWorker := p.cachePool.Get(); cacheWorker != nil { + return cacheWorker.(*Worker) + } + } } else { w = idleWorkers[n] idleWorkers[n] = nil diff --git a/pool_func.go b/pool_func.go index a1750f5..0b7bb4b 100644 --- a/pool_func.go +++ b/pool_func.go @@ -59,6 +59,8 @@ type PoolWithFunc struct { once sync.Once + cachePool sync.Pool + // PanicHandler is used to handle panics from each worker goroutine. // if nil, panics will be thrown out again from worker goroutines. PanicHandler func(interface{}) @@ -198,6 +200,13 @@ func (p *PoolWithFunc) getWorker() *WorkerWithFunc { n := len(idleWorkers) - 1 if n < 0 { waiting = p.Running() >= p.Cap() + if p.Running() >= p.Cap() { + waiting = true + } else { + if cacheWorker := p.cachePool.Get(); cacheWorker != nil { + return cacheWorker.(*WorkerWithFunc) + } + } } else { w = idleWorkers[n] idleWorkers[n] = nil diff --git a/worker.go b/worker.go index eb8f9cc..0d648ba 100644 --- a/worker.go +++ b/worker.go @@ -54,14 +54,15 @@ func (w *Worker) run() { } } }() - + for f := range w.task { if f == nil { w.pool.decRunning() + w.pool.cachePool.Put(w) return } f() w.pool.putWorker(w) } }() -} \ No newline at end of file +} diff --git a/worker_func.go b/worker_func.go index 47ece34..b9c03e0 100644 --- a/worker_func.go +++ b/worker_func.go @@ -54,14 +54,15 @@ func (w *WorkerWithFunc) run() { } } }() - + for args := range w.args { if args == nil { w.pool.decRunning() + w.pool.cachePool.Put(w) return } w.pool.poolFunc(args) w.pool.putWorker(w) } }() -} \ No newline at end of file +}