From 110070cad70a98f453848341c2eef23510f0781f Mon Sep 17 00:00:00 2001 From: qydysky Date: Thu, 18 Feb 2021 00:37:23 +0800 Subject: [PATCH] 106 --- map/Map.go | 15 ++++++++++----- map/Map_test.go | 10 +++++----- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/map/Map.go b/map/Map.go index 16d9c81..97dafdb 100644 --- a/map/Map.go +++ b/map/Map.go @@ -37,7 +37,7 @@ func (t *Map) Store(k,v interface{}) { t.lock.Unlock() } -func (t *Map) Load(k interface{}) (v interface{}) { +func (t *Map) Load(k interface{}) (interface{},bool) { m,_ := t.readOnly.Load().(map[interface{}]*ptr) p,ok := m[k] @@ -60,12 +60,17 @@ func (t *Map) Load(k interface{}) (v interface{}) { } if !ok{ - return nil + return nil,false } return p.tryLoad() } +func (t *Map) LoadV(k interface{}) (v interface{}) { + v,_ = t.Load(k) + return +} + func (t *Map) Delete(k interface{}) { m,_ := t.readOnly.Load().(map[interface{}]*ptr) @@ -103,12 +108,12 @@ func (t *ptr) tryStore(v *interface{}) { // atomic.StorePointer(&t.p, unsafe.Pointer(v)) } -func (t *ptr) tryLoad() (interface{}) { +func (t *ptr) tryLoad() (interface{},bool) { // p := atomic.LoadPointer(&t.p) if t.p == nil{ - return nil + return nil,false } - return *(*interface{})(t.p) + return *(*interface{})(t.p),true } type pLock struct{ diff --git a/map/Map_test.go b/map/Map_test.go index d5aa198..9e6d9a5 100644 --- a/map/Map_test.go +++ b/map/Map_test.go @@ -9,13 +9,13 @@ func Test_customMap(t *testing.T) { var c Map //set c.Store(0, 3) - if c.Load(0) != 3{t.Error(`1`)} + if v,ok := c.Load(0);ok && v != 3{t.Error(`1`)} //change c.Store(0, 1) - if c.Load(0) != 1{t.Error(`2`)} + if v,ok := c.Load(0);ok && v != 1{t.Error(`2`)} //del c.Store(0, nil) - if c.Load(0) != nil{t.Error(`3`)} + if v,ok := c.Load(0);ok && v != nil{t.Error(`3`)} } func Benchmark_customMap_Set(b *testing.B) { @@ -79,7 +79,7 @@ func Benchmark_customMap_Get(b *testing.B) { b.ResetTimer() for i := 0; i < t; i++ { go func(index int) { - if c.Load(index).(int) != index { + if c.LoadV(index).(int) != index { b.Error("q") } w.Done() @@ -113,7 +113,7 @@ func Benchmark_customMap_SetGet(b *testing.B) { w.Done() }(i) go func(index int) { - if t,ok := c.Load(index).(int);!ok || t != index && t != index+1{ + if t,ok := c.LoadV(index).(int);!ok || t != index && t != index+1{ b.Error(`E`, index, t) } w.Done() -- 2.39.2