mirror of https://github.com/panjf2000/ants.git
optimize memory using
This commit is contained in:
parent
91349c14bb
commit
798a61d175
2
ants.go
2
ants.go
|
@ -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)
|
||||||
|
|
||||||
|
|
|
@ -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++ {
|
||||||
|
|
33
pool.go
33
pool.go
|
@ -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()
|
||||||
pool: p,
|
if wp == nil {
|
||||||
task: make(chan f),
|
w = &Worker{
|
||||||
|
pool: p,
|
||||||
|
task: make(chan f),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
w = wp.(*Worker)
|
||||||
}
|
}
|
||||||
worker.run()
|
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()
|
||||||
|
} else {
|
||||||
|
w = workers[n]
|
||||||
|
workers[n] = nil
|
||||||
|
p.workers = workers[:n]
|
||||||
|
atomic.AddInt32(&p.running, 1)
|
||||||
}
|
}
|
||||||
return p.newWorker()
|
p.m.Unlock()
|
||||||
|
return w
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *Pool) putWorker(worker *Worker) {
|
func (p *Pool) putWorker(worker *Worker) {
|
||||||
|
|
16
worker.go
16
worker.go
|
@ -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 {
|
||||||
|
|
Loading…
Reference in New Issue