📚Refactor the blocking logic in retrieveWorker function

This commit is contained in:
Andy Pan 2019-07-27 13:08:09 +08:00
parent 9cfc9fa643
commit 61660e2109
2 changed files with 18 additions and 30 deletions

10
pool.go
View File

@ -211,7 +211,6 @@ func (p *Pool) retrieveWorker() *Worker {
p.lock.Lock() p.lock.Lock()
idleWorkers := p.workers idleWorkers := p.workers
n := len(idleWorkers) - 1 n := len(idleWorkers) - 1
RESUME:
if n >= 0 { if n >= 0 {
w = idleWorkers[n] w = idleWorkers[n]
idleWorkers[n] = nil idleWorkers[n] = nil
@ -229,20 +228,15 @@ RESUME:
} }
w.run() w.run()
} else { } else {
for { Reentry:
if p.Running() == 0 {
goto RESUME
}
p.cond.Wait() p.cond.Wait()
l := len(p.workers) - 1 l := len(p.workers) - 1
if l < 0 { if l < 0 {
continue goto Reentry
} }
w = p.workers[l] w = p.workers[l]
p.workers[l] = nil p.workers[l] = nil
p.workers = p.workers[:l] p.workers = p.workers[:l]
break
}
p.lock.Unlock() p.lock.Unlock()
} }
return w return w

View File

@ -216,7 +216,6 @@ func (p *PoolWithFunc) retrieveWorker() *WorkerWithFunc {
p.lock.Lock() p.lock.Lock()
idleWorkers := p.workers idleWorkers := p.workers
n := len(idleWorkers) - 1 n := len(idleWorkers) - 1
RESUME:
if n >= 0 { if n >= 0 {
w = idleWorkers[n] w = idleWorkers[n]
idleWorkers[n] = nil idleWorkers[n] = nil
@ -234,20 +233,15 @@ RESUME:
} }
w.run() w.run()
} else { } else {
for { Reentry:
if p.Running() == 0 {
goto RESUME
}
p.cond.Wait() p.cond.Wait()
l := len(p.workers) - 1 l := len(p.workers) - 1
if l < 0 { if l < 0 {
continue goto Reentry
} }
w = p.workers[l] w = p.workers[l]
p.workers[l] = nil p.workers[l] = nil
p.workers = p.workers[:l] p.workers = p.workers[:l]
break
}
p.lock.Unlock() p.lock.Unlock()
} }
return w return w