]> 127.0.0.1 Git - part/.git/commitdiff
IDę±  v0.3.7
authorqydysky <qydysky@foxmail.com>
Mon, 1 Feb 2021 13:29:47 +0000 (21:29 +0800)
committerqydysky <qydysky@foxmail.com>
Mon, 1 Feb 2021 13:29:47 +0000 (21:29 +0800)
idpool/Idpool.go [new file with mode: 0644]
idpool/Idpool_test.go [new file with mode: 0644]

diff --git a/idpool/Idpool.go b/idpool/Idpool.go
new file mode 100644 (file)
index 0000000..72fb4fe
--- /dev/null
@@ -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 (file)
index 0000000..ee8e856
--- /dev/null
@@ -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)
+}