diff --git a/ants.go b/ants.go index 7d6b161..5c2248f 100644 --- a/ants.go +++ b/ants.go @@ -10,10 +10,15 @@ func Push(task f) error { return defaultPool.Push(task) } -func Size() int { - return int(defaultPool.Running()) +func Running() int { + return defaultPool.Running() } func Cap() int { - return int(defaultPool.Cap()) + return defaultPool.Cap() } + +func Free() int { + return defaultPool.Free() +} + diff --git a/ants_benchmark_test.go b/ants_benchmark_test.go new file mode 100644 index 0000000..d3306c4 --- /dev/null +++ b/ants_benchmark_test.go @@ -0,0 +1 @@ +package ants diff --git a/ants_test.go b/ants_test.go index 2e071ec..24afdb1 100644 --- a/ants_test.go +++ b/ants_test.go @@ -1,3 +1,53 @@ -package ants +package ants_test -import "testing" +import ( + "testing" + "github.com/panjf2000/ants" + "fmt" + "runtime" +) + +var n = 100000 + +func demoFunc() { + for i := 0; i < 1000000; i++ {} +} + +func TestDefaultPool(t *testing.T) { + for i := 0; i < n; i++ { + ants.Push(demoFunc) + } + + t.Logf("pool capacity:%d", ants.Cap()) + t.Logf("running workers number:%d", ants.Running()) + t.Logf("free workers number:%d", ants.Free()) + + mem := runtime.MemStats{} + runtime.ReadMemStats(&mem) + fmt.Println("memory usage:", mem.TotalAlloc/1024) +} + +//func TestCustomPool(t *testing.T) { +// p := ants.NewPool(1000) +// for i := 0; i < n; i++ { +// p.Push(demoFunc) +// } +// +// t.Logf("pool capacity:%d", p.Cap()) +// t.Logf("running workers number:%d", p.Running()) +// t.Logf("free workers number:%d", p.Free()) +// +// mem := runtime.MemStats{} +// runtime.ReadMemStats(&mem) +// +//} + +func TestNoPool(t *testing.T) { + for i := 0; i < n; i++ { + go demoFunc() + } + mem := runtime.MemStats{} + runtime.ReadMemStats(&mem) + fmt.Println("memory usage:", mem.TotalAlloc/1024) + +} diff --git a/pool.go b/pool.go index 2f5fa26..45bf9f3 100644 --- a/pool.go +++ b/pool.go @@ -56,16 +56,16 @@ func (p *Pool) Push(task f) error { p.tasks <- task return nil } -func (p *Pool) Running() int32 { - return atomic.LoadInt32(&p.running) +func (p *Pool) Running() int { + return int(atomic.LoadInt32(&p.running)) } -func (p *Pool) Free() int32 { - return atomic.LoadInt32(&p.capacity) - atomic.LoadInt32(&p.running) +func (p *Pool) Free() int { + return int(atomic.LoadInt32(&p.capacity) - atomic.LoadInt32(&p.running)) } -func (p *Pool) Cap() int32 { - return atomic.LoadInt32(&p.capacity) +func (p *Pool) Cap() int { + return int(atomic.LoadInt32(&p.capacity)) } func (p *Pool) Destroy() error { @@ -90,11 +90,11 @@ func (p *Pool) newWorker() *Worker { exit: make(chan sig), } worker.run() - atomic.AddInt32(&p.running, 1) return worker } func (p *Pool) getWorker() *Worker { + defer atomic.AddInt32(&p.running, 1) var worker *Worker if p.reachLimit() { worker = <-p.workers