mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-08-19 18:32:23 +00:00
use rwlock
This commit is contained in:
parent
7cfff30ba3
commit
5fc20d4e63
2 changed files with 14 additions and 14 deletions
|
|
@ -36,7 +36,7 @@ type SizeConstrainedCache[K comparable, V blobType] struct {
|
|||
size uint64
|
||||
maxSize uint64
|
||||
lru BasicLRU[K, V]
|
||||
lock sync.Mutex
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// NewSizeConstrainedCache creates a new size-constrained LRU cache.
|
||||
|
|
@ -77,8 +77,8 @@ func (c *SizeConstrainedCache[K, V]) Add(key K, value V) (evicted bool) {
|
|||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *SizeConstrainedCache[K, V]) Get(key K) (V, bool) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
|
||||
return c.lru.Get(key)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ import "sync"
|
|||
// This type is safe for concurrent use.
|
||||
type Cache[K comparable, V any] struct {
|
||||
cache BasicLRU[K, V]
|
||||
mu sync.Mutex
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewCache creates an LRU cache.
|
||||
|
|
@ -40,32 +40,32 @@ func (c *Cache[K, V]) Add(key K, value V) (evicted bool) {
|
|||
|
||||
// Contains reports whether the given key exists in the cache.
|
||||
func (c *Cache[K, V]) Contains(key K) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
return c.cache.Contains(key)
|
||||
}
|
||||
|
||||
// Get retrieves a value from the cache. This marks the key as recently used.
|
||||
func (c *Cache[K, V]) Get(key K) (value V, ok bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
return c.cache.Get(key)
|
||||
}
|
||||
|
||||
// Len returns the current number of items in the cache.
|
||||
func (c *Cache[K, V]) Len() int {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
return c.cache.Len()
|
||||
}
|
||||
|
||||
// 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) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
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.
|
||||
func (c *Cache[K, V]) Keys() []K {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
|
||||
return c.cache.Keys()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue