mirror of https://github.com/panjf2000/ants.git
Refine the logic of sync.Pool
This commit is contained in:
parent
0a946593e2
commit
b1cf2ff445
17
pool.go
17
pool.go
|
@ -147,6 +147,14 @@ func NewPool(size int, options ...Option) (*Pool, error) {
|
||||||
panicHandler: opts.PanicHandler,
|
panicHandler: opts.PanicHandler,
|
||||||
lock: internal.NewSpinLock(),
|
lock: internal.NewSpinLock(),
|
||||||
}
|
}
|
||||||
|
p.workerCache = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return &goWorker{
|
||||||
|
pool: p,
|
||||||
|
task: make(chan func(), workerChanCap),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
if opts.PreAlloc {
|
if opts.PreAlloc {
|
||||||
p.workers = make([]*goWorker, 0, size)
|
p.workers = make([]*goWorker, 0, size)
|
||||||
}
|
}
|
||||||
|
@ -227,14 +235,7 @@ func (p *Pool) decRunning() {
|
||||||
func (p *Pool) retrieveWorker() *goWorker {
|
func (p *Pool) retrieveWorker() *goWorker {
|
||||||
var w *goWorker
|
var w *goWorker
|
||||||
spawnWorker := func() {
|
spawnWorker := func() {
|
||||||
if cacheWorker := p.workerCache.Get(); cacheWorker != nil {
|
w = p.workerCache.Get().(*goWorker)
|
||||||
w = cacheWorker.(*goWorker)
|
|
||||||
} else {
|
|
||||||
w = &goWorker{
|
|
||||||
pool: p,
|
|
||||||
task: make(chan func(), workerChanCap),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.run()
|
w.run()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
17
pool_func.go
17
pool_func.go
|
@ -155,6 +155,14 @@ func NewPoolWithFunc(size int, pf func(interface{}), options ...Option) (*PoolWi
|
||||||
panicHandler: opts.PanicHandler,
|
panicHandler: opts.PanicHandler,
|
||||||
lock: internal.NewSpinLock(),
|
lock: internal.NewSpinLock(),
|
||||||
}
|
}
|
||||||
|
p.workerCache = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return &goWorkerWithFunc{
|
||||||
|
pool: p,
|
||||||
|
args: make(chan interface{}, workerChanCap),
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
if opts.PreAlloc {
|
if opts.PreAlloc {
|
||||||
p.workers = make([]*goWorkerWithFunc, 0, size)
|
p.workers = make([]*goWorkerWithFunc, 0, size)
|
||||||
}
|
}
|
||||||
|
@ -235,14 +243,7 @@ func (p *PoolWithFunc) decRunning() {
|
||||||
func (p *PoolWithFunc) retrieveWorker() *goWorkerWithFunc {
|
func (p *PoolWithFunc) retrieveWorker() *goWorkerWithFunc {
|
||||||
var w *goWorkerWithFunc
|
var w *goWorkerWithFunc
|
||||||
spawnWorker := func() {
|
spawnWorker := func() {
|
||||||
if cacheWorker := p.workerCache.Get(); cacheWorker != nil {
|
w = p.workerCache.Get().(*goWorkerWithFunc)
|
||||||
w = cacheWorker.(*goWorkerWithFunc)
|
|
||||||
} else {
|
|
||||||
w = &goWorkerWithFunc{
|
|
||||||
pool: p,
|
|
||||||
args: make(chan interface{}, workerChanCap),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
w.run()
|
w.run()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue