From 30207f82d1e1c6083caed075cffa92af693cc531 Mon Sep 17 00:00:00 2001 From: Yonder Blue Date: Wed, 30 Mar 2022 16:10:25 -0400 Subject: [PATCH] Allow the caller to lock access --- cache.go | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/cache.go b/cache.go index 0ae51bf..04e8837 100644 --- a/cache.go +++ b/cache.go @@ -58,7 +58,7 @@ type baseCache struct { deserializeFunc DeserializeFunc serializeFunc SerializeFunc expiration *time.Duration - mu sync.RWMutex + mu Locker loadGroup Group *stats } @@ -73,6 +73,19 @@ type ( SerializeFunc func(interface{}, interface{}) (interface{}, error) ) +type Locker interface { + RLock() + RUnlock() + sync.Locker +} + +type noopLocker struct{} + +func (noopLocker) RLock() {} +func (noopLocker) RUnlock() {} +func (noopLocker) Lock() {} +func (noopLocker) Unlock() {} + type CacheBuilder struct { clock Clock tp string @@ -84,16 +97,23 @@ type CacheBuilder struct { expiration *time.Duration deserializeFunc DeserializeFunc serializeFunc SerializeFunc + locker Locker } func New(size int) *CacheBuilder { return &CacheBuilder{ - clock: NewRealClock(), - tp: TYPE_SIMPLE, - size: size, + clock: NewRealClock(), + tp: TYPE_SIMPLE, + size: size, + locker: &sync.RWMutex{}, } } +func (cb *CacheBuilder) NoLock() *CacheBuilder { + cb.locker = noopLocker{} + return cb +} + func (cb *CacheBuilder) Clock(clock Clock) *CacheBuilder { cb.clock = clock return cb @@ -202,6 +222,7 @@ func buildCache(c *baseCache, cb *CacheBuilder) { c.evictedFunc = cb.evictedFunc c.purgeVisitorFunc = cb.purgeVisitorFunc c.stats = &stats{} + c.mu = cb.locker } // load a new value using by specified key.