新增内存池模块

This commit is contained in:
boyce
2021-01-07 10:37:13 +08:00
parent 4116b9ae12
commit e712e24de5

64
util/sync/MemPool.go Normal file
View File

@@ -0,0 +1,64 @@
package sync
type Pool struct {
New func()interface{} //构建对象函数
C chan interface{} //最大缓存的数量
}
type IPoolData interface {
Reset()
IsRef()bool
Ref()
UnRef()
}
type PoolEx struct{
New func()IPoolData //构建对象函数
C chan IPoolData //最大缓存的数量
}
func (pool *Pool) Get() interface{}{
select {
case d := <-pool.C:
return d
default:
return pool.New()
}
return nil
}
func (pool *Pool) Put(data interface{}){
select {
case pool.C <- data:
default:
}
}
func (pool *PoolEx) Get() IPoolData{
select {
case d := <-pool.C:
d.Ref()
d.Reset()
return d
default:
data := pool.New()
data.Reset()
data.Ref()
}
return nil
}
func (pool *PoolEx) Put(data IPoolData){
if data.IsRef() == false {
panic("Repeatedly freeing memory")
}
data.UnRef()
select {
case pool.C <- data:
default:
}
}