From 3edea5370de2415847cc2a2ca1d2cb26a7667299 Mon Sep 17 00:00:00 2001 From: David Symonds Date: Wed, 21 Mar 2012 16:44:07 +1100 Subject: [PATCH] Protect cache map from concurrent access. Go maps are not safe to mutate concurrent with other mutations or reads. --- memg.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/memg.go b/memg.go index db0365c..2ffff3e 100755 --- a/memg.go +++ b/memg.go @@ -8,10 +8,14 @@ import ( "os" "strconv" "strings" + "sync" //"runtime/pprof" // Uncomment to profile ) -var CACHE map[string]string +var ( + mu sync.RWMutex + CACHE map[string]string +) func main() { @@ -87,7 +91,9 @@ func handleConn(conn net.Conn) { case "get": key := parts[1] + mu.RLock() val, ok := CACHE[key] + mu.RUnlock() if ok { length := strconv.Itoa(len(val)) conn.Write([]uint8("VALUE " + key + " 0 " + length + "\r\n")) @@ -103,7 +109,9 @@ func handleConn(conn net.Conn) { // Really we should read exactly 'length' bytes + \r\n val := make([]byte, length) reader.Read(val) + mu.Lock() CACHE[key] = string(val) + mu.Unlock() conn.Write([]uint8("STORED\r\n")) } }