From 8ecd5078ac8f3eacd8037d2bcd5addf87d45a4ae Mon Sep 17 00:00:00 2001 From: liyonglion <470542519@qq.com> Date: Sat, 29 Sep 2018 10:19:17 +0800 Subject: [PATCH] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E6=AD=BB=E9=94=81=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pool.go | 6 ++---- pool_func.go | 24 ++++++++---------------- 2 files changed, 10 insertions(+), 20 deletions(-) diff --git a/pool.go b/pool.go index 5f6ce63..f3d931c 100644 --- a/pool.go +++ b/pool.go @@ -184,6 +184,7 @@ func (p *Pool) getWorker() *Worker { waiting := false p.lock.Lock() + defer p.lock.Unlock() idleWorkers := p.workers n := len(idleWorkers) - 1 if n < 0 { @@ -193,14 +194,11 @@ func (p *Pool) getWorker() *Worker { idleWorkers[n] = nil p.workers = idleWorkers[:n] } - p.lock.Unlock() if waiting { - p.lock.Lock() p.cond.Wait() l := len(p.workers) - 1 w = p.workers[l] - p.lock.Unlock() } else if w == nil { w = &Worker{ pool: p, @@ -217,7 +215,7 @@ func (p *Pool) putWorker(worker *Worker) { worker.recycleTime = time.Now() p.lock.Lock() p.workers = append(p.workers, worker) - p.lock.Unlock() //通知有一个空闲的worker p.cond.Signal() + p.lock.Unlock() } diff --git a/pool_func.go b/pool_func.go index 6051117..d1ed757 100644 --- a/pool_func.go +++ b/pool_func.go @@ -50,7 +50,7 @@ type PoolWithFunc struct { // lock for synchronous operation. lock sync.Mutex - + cond *sync.Cond // pf is the function for processing tasks. poolFunc pf @@ -107,6 +107,7 @@ func NewTimingPoolWithFunc(size, expiry int, f pf) (*PoolWithFunc, error) { expiryDuration: time.Duration(expiry) * time.Second, poolFunc: f, } + p.cond = sync.NewCond(&p.lock) go p.periodicallyPurge() return p, nil } @@ -185,6 +186,7 @@ func (p *PoolWithFunc) getWorker() *WorkerWithFunc { waiting := false p.lock.Lock() + defer p.lock.Unlock() idleWorkers := p.workers n := len(idleWorkers) - 1 if n < 0 { @@ -194,23 +196,11 @@ func (p *PoolWithFunc) getWorker() *WorkerWithFunc { idleWorkers[n] = nil p.workers = idleWorkers[:n] } - p.lock.Unlock() if waiting { - for { - p.lock.Lock() - idleWorkers = p.workers - l := len(idleWorkers) - 1 - if l < 0 { - p.lock.Unlock() - continue - } - w = idleWorkers[l] - idleWorkers[l] = nil - p.workers = idleWorkers[:l] - p.lock.Unlock() - break - } + p.cond.Wait() + l := len(p.workers) - 1 + w = p.workers[l] } else if w == nil { w = &WorkerWithFunc{ pool: p, @@ -227,5 +217,7 @@ func (p *PoolWithFunc) putWorker(worker *WorkerWithFunc) { worker.recycleTime = time.Now() p.lock.Lock() p.workers = append(p.workers, worker) + //通知有一个空闲的worker + p.cond.Signal() p.lock.Unlock() }