From 30bf38e6a8ab8e5bea3692a805c7c9f692d758e5 Mon Sep 17 00:00:00 2001 From: Andy Pan Date: Sun, 27 Jan 2019 00:25:14 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9D=20Performance=20improvement:=20use?= =?UTF-8?q?=20sync.Pool=20to=20cache=20active=20workers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- worker.go | 8 +++++--- worker_func.go | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/worker.go b/worker.go index 0d648ba..62a8d22 100644 --- a/worker.go +++ b/worker.go @@ -23,6 +23,7 @@ package ants import ( + "log" "time" ) @@ -43,6 +44,7 @@ type Worker struct { // run starts a goroutine to repeat the process // that performs the function calls. func (w *Worker) run() { + w.pool.incRunning() go func() { defer func() { if p := recover(); p != nil { @@ -50,7 +52,7 @@ func (w *Worker) run() { if w.pool.PanicHandler != nil { w.pool.PanicHandler(p) } else { - panic(p) + log.Printf("worker exits from a panic: %v", p) } } }() @@ -58,11 +60,11 @@ func (w *Worker) run() { for f := range w.task { if f == nil { w.pool.decRunning() - w.pool.cachePool.Put(w) + w.pool.workerCache.Put(w) return } f() - w.pool.putWorker(w) + w.pool.revertWorker(w) } }() } diff --git a/worker_func.go b/worker_func.go index b9c03e0..5c891d9 100644 --- a/worker_func.go +++ b/worker_func.go @@ -23,6 +23,7 @@ package ants import ( + "log" "time" ) @@ -43,6 +44,7 @@ type WorkerWithFunc struct { // run starts a goroutine to repeat the process // that performs the function calls. func (w *WorkerWithFunc) run() { + w.pool.incRunning() go func() { defer func() { if p := recover(); p != nil { @@ -50,7 +52,7 @@ func (w *WorkerWithFunc) run() { if w.pool.PanicHandler != nil { w.pool.PanicHandler(p) } else { - panic(p) + log.Printf("worker exits from a panic: %v", p) } } }() @@ -58,11 +60,11 @@ func (w *WorkerWithFunc) run() { for args := range w.args { if args == nil { w.pool.decRunning() - w.pool.cachePool.Put(w) + w.pool.workerCache.Put(w) return } w.pool.poolFunc(args) - w.pool.putWorker(w) + w.pool.revertWorker(w) } }() }