Skip to content

Commit

Permalink
solution: use localise sync.Mutex so the Get() is thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
bighelmet7 committed Jun 24, 2022
1 parent 0375653 commit 31fcae5
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
3 changes: 3 additions & 0 deletions 2-race-in-cache/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/bighelmet7/go-concurrency-excercises/2-race-in-cache

go 1.18
10 changes: 9 additions & 1 deletion 2-race-in-cache/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

package main

import "container/list"
import (
"container/list"
"sync"
)

// CacheSize determines how big the cache can grow
const CacheSize = 100
Expand All @@ -26,6 +29,8 @@ type page struct {

// KeyStoreCache is a LRU cache for string key-value pairs
type KeyStoreCache struct {
mu sync.Mutex

cache map[string]*list.Element
pages list.List
load func(string) string
Expand All @@ -41,6 +46,9 @@ func New(load KeyStoreCacheLoader) *KeyStoreCache {

// Get gets the key from cache, loads it from the source if needed
func (k *KeyStoreCache) Get(key string) string {
k.mu.Lock()
defer k.mu.Unlock()

if e, ok := k.cache[key]; ok {
k.pages.MoveToFront(e)
return e.Value.(page).Value
Expand Down

0 comments on commit 31fcae5

Please sign in to comment.