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
const DEFAULT_POOL_SIZE = 50000
const DEFAULT_POOL_SIZE = 5
var defaultPool = NewPool(DEFAULT_POOL_SIZE)

View File

@ -6,7 +6,7 @@ import (
"sync"
)
const RunTimes = 10000
const RunTimes = 100000
func BenchmarkPoolGroutine(b *testing.B) {
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 {
var w *Worker
if p.reachLimit() {
<-p.freeSignal
return p.getWorker()
}
worker := &Worker{
wp := p.workerPool.Get()
if wp == nil {
w = &Worker{
pool: p,
task: make(chan f),
}
worker.run()
} else {
w = wp.(*Worker)
}
w.run()
atomic.AddInt32(&p.running, 1)
return worker
return w
}
func (p *Pool) getWorker() *Worker {
if w := p.workerPool.Get(); w != nil {
return w.(*Worker)
}
var w *Worker
p.m.Lock()
workers := p.workers
n := len(workers) - 1
if n < 0 {
p.m.Unlock()
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) {

View File

@ -9,22 +9,6 @@ type Worker struct {
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() {
go func() {
for f := range w.task {