Skip to content

Commit

Permalink
fix: panic error concurrent map read and map write
Browse files Browse the repository at this point in the history
  • Loading branch information
greene authored and greene committed Oct 4, 2022
1 parent c52ed26 commit 61bb14f
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions gokv.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ func (v *Value) IsExpired() bool {
}

type KV struct {
m map[string]*Value
mutex sync.RWMutex
m map[string]*Value
sync.RWMutex
}

func New() *KV {
Expand All @@ -41,16 +41,19 @@ func New() *KV {
}

func (kv *KV) Get(k string) interface{} {
kv.RLock()
v, ok := kv.m[k]
kv.RUnlock()

if !ok {
return nil
}

if v.IsExpired() {
kv.mutex.Lock()
defer kv.mutex.Unlock()

kv.Lock()
delete(kv.m, k)
kv.Unlock()

return nil
}

Expand All @@ -72,8 +75,8 @@ func (kv *KV) Put(k string, v interface{}, args ...interface{}) bool {
}
}

kv.mutex.Lock()
defer kv.mutex.Unlock()
kv.Lock()
defer kv.Unlock()

kv.m[k] = value

Expand All @@ -97,8 +100,8 @@ func (kv *KV) PutWithUuid(v interface{}, args ...interface{}) (key string, ok bo

key = uuid.NewV4().String()

kv.mutex.Lock()
defer kv.mutex.Unlock()
kv.Lock()
defer kv.Unlock()

kv.m[key] = value

Expand Down

0 comments on commit 61bb14f

Please sign in to comment.