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() }