From e712e24de58ac2d2e2040772c962e79861dce48a Mon Sep 17 00:00:00 2001 From: boyce Date: Thu, 7 Jan 2021 10:37:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=86=85=E5=AD=98=E6=B1=A0?= =?UTF-8?q?=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- util/sync/MemPool.go | 64 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 util/sync/MemPool.go diff --git a/util/sync/MemPool.go b/util/sync/MemPool.go new file mode 100644 index 0000000..ae7315b --- /dev/null +++ b/util/sync/MemPool.go @@ -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: + } +} +