This commit is contained in:
Andy Pan 2018-05-23 00:46:43 +08:00
parent 004caa6636
commit 0453f88168
5 changed files with 16 additions and 8 deletions

View File

@ -25,6 +25,7 @@ package ants
import (
"errors"
"math"
"runtime"
)
const (
@ -68,3 +69,10 @@ var (
ErrPoolSizeInvalid = errors.New("invalid size for pool")
ErrPoolClosed = errors.New("this pool has been closed")
)
var workerArgsCap = func() int {
if runtime.GOMAXPROCS(0) == 1 {
return 0
}
return 1
}()

View File

@ -177,20 +177,19 @@ func (p *Pool) getWorker() *Worker {
if wp == nil {
w = &Worker{
pool: p,
task: make(chan f),
task: make(chan f, workerArgsCap),
}
w.run()
atomic.AddInt32(&p.running, 1)
} else {
w = wp.(*Worker)
}
w.run()
p.workerPool.Put(w)
}
return w
}
// putWorker puts a worker back into free pool, recycling the goroutines.
func (p *Pool) putWorker(worker *Worker) {
p.workerPool.Put(worker)
p.lock.Lock()
p.workers = append(p.workers, worker)
p.lock.Unlock()

View File

@ -178,20 +178,19 @@ func (p *PoolWithFunc) getWorker() *WorkerWithFunc {
if wp == nil {
w = &WorkerWithFunc{
pool: p,
args: make(chan interface{}),
args: make(chan interface{}, workerArgsCap),
}
w.run()
atomic.AddInt32(&p.running, 1)
} else {
w = wp.(*WorkerWithFunc)
}
w.run()
p.workerPool.Put(w)
}
return w
}
// putWorker puts a worker back into free pool, recycling the goroutines.
func (p *PoolWithFunc) putWorker(worker *WorkerWithFunc) {
p.workerPool.Put(worker)
p.lock.Lock()
p.workers = append(p.workers, worker)
p.lock.Unlock()

View File

@ -40,6 +40,7 @@ type Worker struct {
// run will start a goroutine to repeat the process
// that perform the function calls.
func (w *Worker) run() {
atomic.AddInt32(&w.pool.running, 1)
go func() {
for f := range w.task {
if f == nil {

View File

@ -40,6 +40,7 @@ type WorkerWithFunc struct {
// run will start a goroutine to repeat the process
// that perform the function calls.
func (w *WorkerWithFunc) run() {
atomic.AddInt32(&w.pool.running, 1)
go func() {
for args := range w.args {
if args == nil {