Skip to content

Commit

Permalink
Refine the logic of sync.Pool
Browse files Browse the repository at this point in the history
  • Loading branch information
panjf2000 committed Oct 5, 2019
1 parent 0a94659 commit b1cf2ff
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 16 deletions.
17 changes: 9 additions & 8 deletions pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()
}

Expand Down
17 changes: 9 additions & 8 deletions pool_func.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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()
}

Expand Down

0 comments on commit b1cf2ff

Please sign in to comment.