forked from mirror/ants
optimize memory using
This commit is contained in:
parent
91349c14bb
commit
798a61d175
2
ants.go
2
ants.go
|
@ -1,6 +1,6 @@
|
|||
package ants
|
||||
|
||||
const DEFAULT_POOL_SIZE = 50000
|
||||
const DEFAULT_POOL_SIZE = 5
|
||||
|
||||
var defaultPool = NewPool(DEFAULT_POOL_SIZE)
|
||||
|
||||
|
|
|
@ -6,7 +6,7 @@ import (
|
|||
"sync"
|
||||
)
|
||||
|
||||
const RunTimes = 10000
|
||||
const RunTimes = 100000
|
||||
|
||||
func BenchmarkPoolGroutine(b *testing.B) {
|
||||
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 {
|
||||
var w *Worker
|
||||
if p.reachLimit() {
|
||||
<-p.freeSignal
|
||||
return p.getWorker()
|
||||
}
|
||||
worker := &Worker{
|
||||
pool: p,
|
||||
task: make(chan f),
|
||||
wp := p.workerPool.Get()
|
||||
if wp == nil {
|
||||
w = &Worker{
|
||||
pool: p,
|
||||
task: make(chan f),
|
||||
}
|
||||
} else {
|
||||
w = wp.(*Worker)
|
||||
}
|
||||
worker.run()
|
||||
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)
|
||||
}
|
||||
return p.newWorker()
|
||||
p.m.Unlock()
|
||||
return w
|
||||
}
|
||||
|
||||
func (p *Pool) putWorker(worker *Worker) {
|
||||
|
|
16
worker.go
16
worker.go
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue