解决死锁问题

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

View File

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