From 69e59822f09d1d958fb190f59191b73441f59ecd Mon Sep 17 00:00:00 2001 From: siddharth ravikumar Date: Mon, 26 Dec 2022 16:40:40 -0500 Subject: cache: make it concurrency safe --- cache/cache.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'cache/cache.go') diff --git a/cache/cache.go b/cache/cache.go index 8f29ee4..8d5e8f8 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -14,12 +14,14 @@ type item struct { // A key-value cache store. type Cache struct { + sema chan int // Semaphore for read/write access to cache. store map[string]item } // Returns a new empty cache store. func NewCache() *Cache { c := new(Cache) + c.sema = make(chan int, 1) c.store = make(map[string]item) return c } @@ -30,6 +32,12 @@ func NewCache() *Cache { // Cache.Get will return an empty string once `expires` is past the // current time. func (c *Cache) Set(key string, value []byte, expires time.Time) { + // Get sema token before accessing the cache. + c.sema <- 1 + defer func() { + // Give up sema token. + <-c.sema + }() c.store[key] = item{ value: value, expires: expires, @@ -41,6 +49,13 @@ func (c *Cache) Set(key string, value []byte, expires time.Time) { // An empty []byte will be returned when if the key does not exist or // if the item corresponding to the key has expired. func (c *Cache) Get(key string) []byte { + // Get sema token before accessing the cache. + c.sema <- 1 + defer func() { + // Give up sema token. + <-c.sema + }() + if _, ok := c.store[key]; !ok { return []byte{} } -- cgit v1.2.3