修复移除内存缓存死锁的Bug

This commit is contained in:
GoEdgeLab
2021-06-17 18:04:56 +08:00
parent 1b9a14efda
commit a40fe3cf26
2 changed files with 34 additions and 4 deletions

View File

@@ -77,10 +77,9 @@ func (this *MemoryStorage) OpenReader(key string) (Reader, error) {
hash := this.hash(key) hash := this.hash(key)
this.locker.RLock() this.locker.RLock()
defer this.locker.RUnlock()
item := this.valuesMap[hash] item := this.valuesMap[hash]
if item == nil || !item.IsDone { if item == nil || !item.IsDone {
this.locker.RUnlock()
return nil, ErrNotFound return nil, ErrNotFound
} }
@@ -88,10 +87,13 @@ func (this *MemoryStorage) OpenReader(key string) (Reader, error) {
reader := NewMemoryReader(item) reader := NewMemoryReader(item)
err := reader.Init() err := reader.Init()
if err != nil { if err != nil {
this.locker.RUnlock()
return nil, err return nil, err
} }
this.locker.RUnlock()
return reader, nil return reader, nil
} }
this.locker.RUnlock()
_ = this.Delete(key) _ = this.Delete(key)
@@ -137,7 +139,7 @@ func (this *MemoryStorage) OpenWriter(key string, expiredAt int64, status int) (
} }
// 先删除 // 先删除
err = this.deleteWithoutKey(key) err = this.deleteWithoutLocker(key)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -276,7 +278,7 @@ func (this *MemoryStorage) memoryCapacityBytes() int64 {
return c1 return c1
} }
func (this *MemoryStorage) deleteWithoutKey(key string) error { func (this *MemoryStorage) deleteWithoutLocker(key string) error {
hash := this.hash(key) hash := this.hash(key)
delete(this.valuesMap, hash) delete(this.valuesMap, hash)
_ = this.list.Remove(fmt.Sprintf("%d", hash)) _ = this.list.Remove(fmt.Sprintf("%d", hash))

View File

@@ -84,6 +84,19 @@ func TestMemoryStorage_OpenWriter(t *testing.T) {
} }
} }
func TestMemoryStorage_OpenReaderLock(t *testing.T) {
storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{})
_ = storage.Init()
var h = storage.hash("test")
storage.valuesMap = map[uint64]*MemoryItem{
h: {
IsDone: true,
},
}
_, _ = storage.OpenReader("test")
}
func TestMemoryStorage_Delete(t *testing.T) { func TestMemoryStorage_Delete(t *testing.T) {
storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{}) storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{})
{ {
@@ -237,3 +250,18 @@ func TestMemoryStorage_Expire(t *testing.T) {
} }
time.Sleep(70 * time.Second) time.Sleep(70 * time.Second)
} }
func TestMemoryStorage_Locker(t *testing.T) {
storage := NewMemoryStorage(&serverconfigs.HTTPCachePolicy{})
err := storage.Init()
if err != nil {
t.Fatal(err)
}
storage.locker.Lock()
err = storage.deleteWithoutLocker("a")
storage.locker.Unlock()
if err != nil {
t.Fatal(err)
}
t.Log("ok")
}