优化内存池

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)
}
}