crossoverJie / ptg

💥Performance testing tool (Go), It is also a GUI gRPC client.
https://crossoverjie.top/2021/11/28/go/go-grpc-client-gui/
329 stars 37 forks source link

LRU 模块Put 方法有 bug #9

Open shuhaohe opened 2 years ago

shuhaohe commented 2 years ago
func (l *LruCache) Put(k, v interface{}) {
    l.lock.Lock()
    defer l.lock.Unlock()
    if l.values.Len() == l.size {
        back := l.values.Back()
        l.values.Remove(back)
        delete(l.cacheMap, back)  // 这里试图删除 back 这个元素。但是通常来说,back 元素本身不会是 map 的 key
    }

    front := l.values.PushFront(v)
    l.cacheMap[k] = front
}
cz321 commented 1 year ago

我做了修改解决了这个bug:


func (l *LRUCache) Put(k,v interface{}) {
    l.lock.Lock()
    defer l.lock.Unlock()

        if e,ok := l.cacheMap[k]; ok {
        l.values.Remove(e)
        delete(l.cacheMap,e.Value.(Pair).Key)
    }

    if l.values.Len() == l.cap {
        back := l.values.Back()
        l.values.Remove(back)
        delete(l.cacheMap,back.Value.(Pair).Key)
    }
    front := l.values.PushFront(Pair{
        Key: k,
        Val: v,
    })
    l.cacheMap[k] = front
}

type Pair struct {
    Key,Val interface{}
}
crossoverJie commented 1 year ago

@cz321 欢迎提 PR