From f65aad778bc77785eaa1939ea3695c404bf9ab36 Mon Sep 17 00:00:00 2001 From: Thomas Rudin Date: Fri, 22 Mar 2019 17:32:43 +0100 Subject: [PATCH] add rw-lock to mapblockaccessor, fixes #23 --- server/mapblockaccessor/get.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/server/mapblockaccessor/get.go b/server/mapblockaccessor/get.go index f6f8a93..6e16e2f 100644 --- a/server/mapblockaccessor/get.go +++ b/server/mapblockaccessor/get.go @@ -4,15 +4,19 @@ import ( "mapserver/coords" "mapserver/eventbus" "mapserver/mapblockparser" + "sync" cache "github.com/patrickmn/go-cache" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) +var lock = &sync.RWMutex{} + func (a *MapBlockAccessor) GetMapBlock(pos *coords.MapBlockCoords) (*mapblockparser.MapBlock, error) { key := getKey(pos) + //maintenance cacheBlocks.Set(float64(a.blockcache.ItemCount())) if a.blockcache.ItemCount() > a.maxcount { //flush cache @@ -25,8 +29,13 @@ func (a *MapBlockAccessor) GetMapBlock(pos *coords.MapBlockCoords) (*mapblockpar a.blockcache.Flush() } + //read section + lock.RLock() + cachedblock, found := a.blockcache.Get(key) if found { + defer lock.RUnlock() + getCacheHitCount.Inc() if cachedblock == nil { return nil, nil @@ -35,9 +44,27 @@ func (a *MapBlockAccessor) GetMapBlock(pos *coords.MapBlockCoords) (*mapblockpar } } + //end read + lock.RUnlock() + timer := prometheus.NewTimer(dbGetDuration) defer timer.ObserveDuration() + //write section + lock.Lock() + defer lock.Unlock() + + //try read + cachedblock, found = a.blockcache.Get(key) + if found { + getCacheHitCount.Inc() + if cachedblock == nil { + return nil, nil + } else { + return cachedblock.(*mapblockparser.MapBlock), nil + } + } + block, err := a.accessor.GetBlock(pos) if err != nil { return nil, err