Refine the logic of sync.Pool

This commit is contained in:
Andy Pan 2019-10-06 02:02:40 +08:00
parent 0a946593e2
commit b1cf2ff445
2 changed files with 18 additions and 16 deletions

17
pool.go
View File

@ -147,6 +147,14 @@ func NewPool(size int, options ...Option) (*Pool, error) {
panicHandler: opts.PanicHandler,
lock: internal.NewSpinLock(),
}
p.workerCache = sync.Pool{
New: func() interface{} {
return &goWorker{
pool: p,
task: make(chan func(), workerChanCap),
}
},
}
if opts.PreAlloc {
p.workers = make([]*goWorker, 0, size)
}
@ -227,14 +235,7 @@ func (p *Pool) decRunning() {
func (p *Pool) retrieveWorker() *goWorker {
var w *goWorker
spawnWorker := func() {
if cacheWorker := p.workerCache.Get(); cacheWorker != nil {
w = cacheWorker.(*goWorker)
} else {
w = &goWorker{
pool: p,
task: make(chan func(), workerChanCap),
}
}
w = p.workerCache.Get().(*goWorker)
w.run()
}

View File

@ -155,6 +155,14 @@ func NewPoolWithFunc(size int, pf func(interface{}), options ...Option) (*PoolWi
panicHandler: opts.PanicHandler,
lock: internal.NewSpinLock(),
}
p.workerCache = sync.Pool{
New: func() interface{} {
return &goWorkerWithFunc{
pool: p,
args: make(chan interface{}, workerChanCap),
}
},
}
if opts.PreAlloc {
p.workers = make([]*goWorkerWithFunc, 0, size)
}
@ -235,14 +243,7 @@ func (p *PoolWithFunc) decRunning() {
func (p *PoolWithFunc) retrieveWorker() *goWorkerWithFunc {
var w *goWorkerWithFunc
spawnWorker := func() {
if cacheWorker := p.workerCache.Get(); cacheWorker != nil {
w = cacheWorker.(*goWorkerWithFunc)
} else {
w = &goWorkerWithFunc{
pool: p,
args: make(chan interface{}, workerChanCap),
}
}
w = p.workerCache.Get().(*goWorkerWithFunc)
w.run()
}