diff options
author | siddharth ravikumar <s@ricketyspace.net> | 2022-12-26 16:40:40 -0500 |
---|---|---|
committer | siddharth ravikumar <s@ricketyspace.net> | 2022-12-26 16:40:40 -0500 |
commit | 69e59822f09d1d958fb190f59191b73441f59ecd (patch) | |
tree | a9134dbd1399cd95aa7d07e1b30dc2ae4ebbaf6e /cache/cache.go | |
parent | a19eb2afbd4c87f7361942eedd7bdc80f3e225cf (diff) |
cache: make it concurrency safe
Diffstat (limited to 'cache/cache.go')
-rw-r--r-- | cache/cache.go | 15 |
1 files changed, 15 insertions, 0 deletions
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{} } |