From: qydysky Date: Mon, 1 Feb 2021 13:29:47 +0000 (+0800) Subject: ID池 X-Git-Tag: v0.3.7 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=267c528a6881206391b354d3e1c8155a3e5e79ad;p=part%2F.git ID池 --- diff --git a/idpool/Idpool.go b/idpool/Idpool.go new file mode 100644 index 0000000..72fb4fe --- /dev/null +++ b/idpool/Idpool.go @@ -0,0 +1,47 @@ +package part + +import ( + "sync" + "unsafe" +) + +type Idpool struct { + pool sync.Pool + sum uint + sync.Mutex +} + +type Id struct { + Id uintptr + item interface{} +} + +func New() (*Idpool) { + return &Idpool{ + pool:sync.Pool{ + New: func() interface{} { + return new(struct{}) + }, + }, + } +} + +func (t *Idpool) Get() (o Id) { + o.item = t.pool.Get() + o.Id = uintptr(unsafe.Pointer(&o.item)) + t.Lock() + t.sum += 1 + t.Unlock() + return +} + +func (t *Idpool) Put(i Id) { + t.pool.Put(i.item) + t.Lock() + t.sum -= 1 + t.Unlock() +} + +func (t *Idpool) Len() uint { + return t.sum +} \ No newline at end of file diff --git a/idpool/Idpool_test.go b/idpool/Idpool_test.go new file mode 100644 index 0000000..ee8e856 --- /dev/null +++ b/idpool/Idpool_test.go @@ -0,0 +1,19 @@ +package part + +import ( + "testing" +) + +func Test(t *testing.T){ + pool := New() + a := pool.Get() + b := pool.Get() + t.Log(a.Id,a.item,pool.Len()) + t.Log(b.Id,b.item) + pool.Put(a) + t.Log(a.Id,a.item,pool.Len()) + t.Log(b.Id,b.item) + a = pool.Get() + t.Log(a.Id,a.item,pool.Len()) + t.Log(b.Id,b.item) +}