优化内存池

This commit is contained in:
boyce
2021-01-07 18:34:32 +08:00
parent e712e24de5
commit e6c01c9071
3 changed files with 118 additions and 25 deletions

View File

@@ -1,5 +1,7 @@
package sync
import sysSync "sync"
type Pool struct {
New func()interface{} //构建对象函数
C chan interface{} //最大缓存的数量
@@ -12,11 +14,12 @@ type IPoolData interface {
UnRef()
}
type PoolEx struct{
New func()IPoolData //构建对象函数
type poolEx struct{
C chan IPoolData //最大缓存的数量
syncPool sysSync.Pool
}
func (pool *Pool) Get() interface{}{
select {
case d := <-pool.C:
@@ -35,22 +38,33 @@ func (pool *Pool) Put(data interface{}){
}
}
func (pool *PoolEx) Get() IPoolData{
func NewPoolEx(C chan IPoolData,New func()IPoolData) *poolEx{
var pool poolEx
pool.C = C
//pool.New = New
pool.syncPool.New = func() interface{} {
return New()
}
return &pool
}
func (pool *poolEx) Get() IPoolData{
select {
case d := <-pool.C:
d.Ref()
d.Reset()
return d
default:
data := pool.New()
data := pool.syncPool.Get().(IPoolData)
data.Reset()
data.Ref()
return data
}
return nil
}
func (pool *PoolEx) Put(data IPoolData){
func (pool *poolEx) Put(data IPoolData){
if data.IsRef() == false {
panic("Repeatedly freeing memory")
}
@@ -59,6 +73,8 @@ func (pool *PoolEx) Put(data IPoolData){
select {
case pool.C <- data:
default:
pool.syncPool.Put(data)
}
}

View File

@@ -2,9 +2,10 @@ package timer
import (
"fmt"
"github.com/duanhf2012/origin/util/sync"
"reflect"
"runtime"
"sync"
"time"
)
@@ -18,6 +19,8 @@ type Timer struct {
cb func()
AdditionData interface{} //定时器附加数据
rOpen bool //是否重新打开
ref bool
}
// Ticker
@@ -30,17 +33,17 @@ type Cron struct {
Timer
}
var timerPool = sync.Pool{New: func() interface{}{
var timerPool = sync.NewPoolEx(make(chan sync.IPoolData,1000),func() sync.IPoolData{
return &Timer{}
}}
})
var cronPool = sync.Pool{New: func() interface{}{
var cronPool = sync.NewPoolEx(make(chan sync.IPoolData,1000),func() sync.IPoolData{
return &Cron{}
}}
})
var tickerPool = sync.Pool{New: func() interface{}{
var tickerPool =sync.NewPoolEx(make(chan sync.IPoolData,1000),func() sync.IPoolData{
return &Ticker{}
}}
})
func newTimer(d time.Duration,c chan *Timer,cb func(),name string,additionData interface{}) *Timer{
if c == nil {
@@ -116,6 +119,53 @@ func (t *Timer) GetName() string{
return t.name
}
func (t *Timer) Reset(){
}
func (t *Timer) IsRef()bool{
return t.ref
}
func (t *Timer) Ref(){
t.ref = true
}
func (t *Timer) UnRef(){
t.ref = false
}
func (c *Cron) Reset(){
}
func (c *Cron) IsRef()bool{
return c.ref
}
func (c *Cron) Ref(){
c.ref = true
}
func (c *Cron) UnRef(){
c.ref = false
}
func (c *Ticker) Reset(){
}
func (c *Ticker) IsRef()bool{
return c.ref
}
func (c *Ticker) Ref(){
c.ref = true
}
func (c *Ticker) UnRef(){
c.ref = false
}
func NewDispatcher(l int) *Dispatcher {
disp := new(Dispatcher)
disp.ChanTimer = make(chan *Timer, l)