Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LRU 模块Put 方法有 bug #9

Open
shuhaohe opened this issue Sep 12, 2022 · 2 comments
Open

LRU 模块Put 方法有 bug #9

shuhaohe opened this issue Sep 12, 2022 · 2 comments
Labels
bug Something isn't working

Comments

@shuhaohe
Copy link

shuhaohe commented Sep 12, 2022

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
}
@crossoverJie crossoverJie added the bug Something isn't working label Sep 16, 2022
@cz321
Copy link

cz321 commented Mar 16, 2023

我做了修改解决了这个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
Copy link
Owner

@cz321 欢迎提 PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants