Maps / Concurrent access of maps / Essential Go

Run Settings
LanguageGo
Language Version
Run Command
package main import ( "fmt" "sync" ) // ConcurrentMap is a wrapper around map that is safe for concurrent use type ConcurrentMap struct { sync.RWMutex m map[string]int } // Get gets a value for a key func (r *ConcurrentMap) Get(key string) int { r.RLock() defer r.RUnlock() return r.m[key] } // Set sets a key to a given value func (r *ConcurrentMap) Set(key string, val int) { r.Lock() defer r.Unlock() r.m[key] = val } // Add increases the value under a key by n func (r *ConcurrentMap) Add(key string, n int) int { r.Lock() defer r.Unlock() r.m[key] += n return r.m[key] } func main() { counter := ConcurrentMap{m: make(map[string]int)} n := counter.Add("some_key", 2) fmt.Printf("Final value is: %d\n", n) }
Editor Settings
Theme
Key bindings
Full width
Lines