解决死锁问题

This commit is contained in:
liyonglion 2018-09-29 10:19:17 +08:00
parent 70731aff71
commit 8ecd5078ac
2 changed files with 10 additions and 20 deletions

View File

@ -184,6 +184,7 @@ func (p *Pool) getWorker() *Worker {
waiting := false waiting := false
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock()
idleWorkers := p.workers idleWorkers := p.workers
n := len(idleWorkers) - 1 n := len(idleWorkers) - 1
if n < 0 { if n < 0 {
@ -193,14 +194,11 @@ func (p *Pool) getWorker() *Worker {
idleWorkers[n] = nil idleWorkers[n] = nil
p.workers = idleWorkers[:n] p.workers = idleWorkers[:n]
} }
p.lock.Unlock()
if waiting { if waiting {
p.lock.Lock()
p.cond.Wait() p.cond.Wait()
l := len(p.workers) - 1 l := len(p.workers) - 1
w = p.workers[l] w = p.workers[l]
p.lock.Unlock()
} else if w == nil { } else if w == nil {
w = &Worker{ w = &Worker{
pool: p, pool: p,
@ -217,7 +215,7 @@ func (p *Pool) putWorker(worker *Worker) {
worker.recycleTime = time.Now() worker.recycleTime = time.Now()
p.lock.Lock() p.lock.Lock()
p.workers = append(p.workers, worker) p.workers = append(p.workers, worker)
p.lock.Unlock()
//通知有一个空闲的worker //通知有一个空闲的worker
p.cond.Signal() p.cond.Signal()
p.lock.Unlock()
} }

View File

@ -50,7 +50,7 @@ type PoolWithFunc struct {
// lock for synchronous operation. // lock for synchronous operation.
lock sync.Mutex lock sync.Mutex
cond *sync.Cond
// pf is the function for processing tasks. // pf is the function for processing tasks.
poolFunc pf poolFunc pf
@ -107,6 +107,7 @@ func NewTimingPoolWithFunc(size, expiry int, f pf) (*PoolWithFunc, error) {
expiryDuration: time.Duration(expiry) * time.Second, expiryDuration: time.Duration(expiry) * time.Second,
poolFunc: f, poolFunc: f,
} }
p.cond = sync.NewCond(&p.lock)
go p.periodicallyPurge() go p.periodicallyPurge()
return p, nil return p, nil
} }
@ -185,6 +186,7 @@ func (p *PoolWithFunc) getWorker() *WorkerWithFunc {
waiting := false waiting := false
p.lock.Lock() p.lock.Lock()
defer p.lock.Unlock()
idleWorkers := p.workers idleWorkers := p.workers
n := len(idleWorkers) - 1 n := len(idleWorkers) - 1
if n < 0 { if n < 0 {
@ -194,23 +196,11 @@ func (p *PoolWithFunc) getWorker() *WorkerWithFunc {
idleWorkers[n] = nil idleWorkers[n] = nil
p.workers = idleWorkers[:n] p.workers = idleWorkers[:n]
} }
p.lock.Unlock()
if waiting { if waiting {
for { p.cond.Wait()
p.lock.Lock() l := len(p.workers) - 1
idleWorkers = p.workers w = p.workers[l]
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
}
} else if w == nil { } else if w == nil {
w = &WorkerWithFunc{ w = &WorkerWithFunc{
pool: p, pool: p,
@ -227,5 +217,7 @@ func (p *PoolWithFunc) putWorker(worker *WorkerWithFunc) {
worker.recycleTime = time.Now() worker.recycleTime = time.Now()
p.lock.Lock() p.lock.Lock()
p.workers = append(p.workers, worker) p.workers = append(p.workers, worker)
//通知有一个空闲的worker
p.cond.Signal()
p.lock.Unlock() p.lock.Unlock()
} }