ants/pool.go

110 lines
1.9 KiB
Go
Raw Normal View History

2018-05-19 07:28:03 +03:00
package ants
import (
"runtime"
"sync/atomic"
"sync"
)
type sig struct{}
type f func()
type Pool struct {
capacity int32
2018-05-19 08:09:44 +03:00
running int32
2018-05-19 07:28:03 +03:00
tasks chan f
workers chan *Worker
destroy chan sig
m sync.Mutex
}
func NewPool(size int) *Pool {
p := &Pool{
capacity: int32(size),
2018-05-19 10:57:04 +03:00
tasks: make(chan f, 1000),
2018-05-19 07:28:03 +03:00
//workers: &sync.Pool{New: func() interface{} { return &Worker{} }},
workers: make(chan *Worker, size),
destroy: make(chan sig, runtime.GOMAXPROCS(-1)),
}
p.loop()
return p
}
//-------------------------------------------------------------------------
func (p *Pool) loop() {
for i := 0; i < runtime.GOMAXPROCS(-1); i++ {
go func() {
for {
select {
case task := <-p.tasks:
p.getWorker().sendTask(task)
case <-p.destroy:
return
}
}
}()
}
}
func (p *Pool) Push(task f) error {
if len(p.destroy) > 0 {
return nil
}
p.tasks <- task
return nil
}
2018-05-19 10:22:14 +03:00
func (p *Pool) Running() int {
return int(atomic.LoadInt32(&p.running))
2018-05-19 07:57:01 +03:00
}
2018-05-19 10:22:14 +03:00
func (p *Pool) Free() int {
return int(atomic.LoadInt32(&p.capacity) - atomic.LoadInt32(&p.running))
2018-05-19 07:28:03 +03:00
}
2018-05-19 10:22:14 +03:00
func (p *Pool) Cap() int {
return int(atomic.LoadInt32(&p.capacity))
2018-05-19 07:28:03 +03:00
}
func (p *Pool) Destroy() error {
p.m.Lock()
defer p.m.Unlock()
2018-05-19 07:57:01 +03:00
for i := 0; i < runtime.GOMAXPROCS(-1)+1; i++ {
2018-05-19 07:28:03 +03:00
p.destroy <- sig{}
}
return nil
}
//-------------------------------------------------------------------------
func (p *Pool) reachLimit() bool {
2018-05-19 07:57:01 +03:00
return p.Running() >= p.Cap()
2018-05-19 07:28:03 +03:00
}
func (p *Pool) newWorker() *Worker {
worker := &Worker{
pool: p,
task: make(chan f),
exit: make(chan sig),
}
worker.run()
return worker
}
func (p *Pool) getWorker() *Worker {
2018-05-19 10:22:14 +03:00
defer atomic.AddInt32(&p.running, 1)
2018-05-19 07:28:03 +03:00
var worker *Worker
2018-05-19 08:09:44 +03:00
if p.reachLimit() {
2018-05-19 08:11:21 +03:00
worker = <-p.workers
} else {
2018-05-19 08:09:44 +03:00
select {
2018-05-19 08:11:21 +03:00
case worker = <-p.workers:
return worker
2018-05-19 08:09:44 +03:00
default:
worker = p.newWorker()
}
2018-05-19 07:28:03 +03:00
}
return worker
}