optimize memory using

This commit is contained in:
Andy Pan 2018-05-20 03:35:31 +08:00
parent 91349c14bb
commit 798a61d175
4 changed files with 27 additions and 26 deletions

View File

@ -1,6 +1,6 @@
package ants package ants
const DEFAULT_POOL_SIZE = 50000 const DEFAULT_POOL_SIZE = 5
var defaultPool = NewPool(DEFAULT_POOL_SIZE) var defaultPool = NewPool(DEFAULT_POOL_SIZE)

View File

@ -6,7 +6,7 @@ import (
"sync" "sync"
) )
const RunTimes = 10000 const RunTimes = 100000
func BenchmarkPoolGroutine(b *testing.B) { func BenchmarkPoolGroutine(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {

29
pool.go
View File

@ -76,24 +76,41 @@ func (p *Pool) reachLimit() bool {
} }
func (p *Pool) newWorker() *Worker { func (p *Pool) newWorker() *Worker {
var w *Worker
if p.reachLimit() { if p.reachLimit() {
<-p.freeSignal <-p.freeSignal
return p.getWorker() return p.getWorker()
} }
worker := &Worker{ wp := p.workerPool.Get()
if wp == nil {
w = &Worker{
pool: p, pool: p,
task: make(chan f), task: make(chan f),
} }
worker.run() } else {
w = wp.(*Worker)
}
w.run()
atomic.AddInt32(&p.running, 1) atomic.AddInt32(&p.running, 1)
return worker return w
} }
func (p *Pool) getWorker() *Worker { func (p *Pool) getWorker() *Worker {
if w := p.workerPool.Get(); w != nil { var w *Worker
return w.(*Worker) p.m.Lock()
} workers := p.workers
n := len(workers) - 1
if n < 0 {
p.m.Unlock()
return p.newWorker() return p.newWorker()
} else {
w = workers[n]
workers[n] = nil
p.workers = workers[:n]
atomic.AddInt32(&p.running, 1)
}
p.m.Unlock()
return w
} }
func (p *Pool) putWorker(worker *Worker) { func (p *Pool) putWorker(worker *Worker) {

View File

@ -9,22 +9,6 @@ type Worker struct {
task chan f task chan f
} }
//func (w *Worker) run() {
// go func() {
// for {
// select {
// case f := <-w.task:
// f()
// w.pool.putWorker(w)
// w.pool.wg.Done()
// case <-w.exit:
// atomic.AddInt32(&w.pool.running, -1)
// return
// }
// }
// }()
//}
func (w *Worker) run() { func (w *Worker) run() {
go func() { go func() {
for f := range w.task { for f := range w.task {