mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-08-20 10:52:25 +00:00
optimize lru with rwlock
This commit is contained in:
parent
a3829178af
commit
e7a333a6e8
1 changed files with 9 additions and 9 deletions
|
|
@ -22,7 +22,7 @@ import "sync"
|
||||||
// This type is safe for concurrent use.
|
// This type is safe for concurrent use.
|
||||||
type Cache[K comparable, V any] struct {
|
type Cache[K comparable, V any] struct {
|
||||||
cache BasicLRU[K, V]
|
cache BasicLRU[K, V]
|
||||||
mu sync.Mutex
|
mu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCache creates an LRU cache.
|
// NewCache creates an LRU cache.
|
||||||
|
|
@ -40,8 +40,8 @@ func (c *Cache[K, V]) Add(key K, value V) (evicted bool) {
|
||||||
|
|
||||||
// Contains reports whether the given key exists in the cache.
|
// Contains reports whether the given key exists in the cache.
|
||||||
func (c *Cache[K, V]) Contains(key K) bool {
|
func (c *Cache[K, V]) Contains(key K) bool {
|
||||||
c.mu.Lock()
|
c.mu.RLock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.RUnlock()
|
||||||
|
|
||||||
return c.cache.Contains(key)
|
return c.cache.Contains(key)
|
||||||
}
|
}
|
||||||
|
|
@ -56,16 +56,16 @@ func (c *Cache[K, V]) Get(key K) (value V, ok bool) {
|
||||||
|
|
||||||
// Len returns the current number of items in the cache.
|
// Len returns the current number of items in the cache.
|
||||||
func (c *Cache[K, V]) Len() int {
|
func (c *Cache[K, V]) Len() int {
|
||||||
c.mu.Lock()
|
c.mu.RLock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.RUnlock()
|
||||||
|
|
||||||
return c.cache.Len()
|
return c.cache.Len()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Peek retrieves a value from the cache, but does not mark the key as recently used.
|
// Peek retrieves a value from the cache, but does not mark the key as recently used.
|
||||||
func (c *Cache[K, V]) Peek(key K) (value V, ok bool) {
|
func (c *Cache[K, V]) Peek(key K) (value V, ok bool) {
|
||||||
c.mu.Lock()
|
c.mu.RLock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.RUnlock()
|
||||||
|
|
||||||
return c.cache.Peek(key)
|
return c.cache.Peek(key)
|
||||||
}
|
}
|
||||||
|
|
@ -88,8 +88,8 @@ func (c *Cache[K, V]) Remove(key K) bool {
|
||||||
|
|
||||||
// Keys returns all keys of items currently in the LRU.
|
// Keys returns all keys of items currently in the LRU.
|
||||||
func (c *Cache[K, V]) Keys() []K {
|
func (c *Cache[K, V]) Keys() []K {
|
||||||
c.mu.Lock()
|
c.mu.RLock()
|
||||||
defer c.mu.Unlock()
|
defer c.mu.RUnlock()
|
||||||
|
|
||||||
return c.cache.Keys()
|
return c.cache.Keys()
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue