Mutexes and concurrent access in Go
Golang has mutexes (short for mutually exclusion) to manage concurrent access to a shared object via multiple goroutines. Here’s an example (taken from the excellent Go by Example: Mutexes). package main import ( "fmt" "sync" ) type Counter struct { mu sync.Mutex count map[string]int } func (c *Counter) Inc(name string) { c.mu.Lock() defer c.mu.Unlock() c.count[name]++ } func main() { cnt := Counter{count: map[string]int{"james": 0, "spartacus": 0}} var wg sync.WaitGroup increment := func(name string, n int) { for i := 0 ; i < n ; i++ { cnt.Inc(name) } wg.Done() } wg.Add(3) go increment("james", 100000) go increment("james", 100000) go increment("spartacus", 10000) wg.Wait() fmt.Println(cnt) } This code defines a simple Counter struct with a single method named Inc to increment the count map. Inc is responsible for managing the locking and unlocking of the mutex with c.mu.Lock() to lock it and defer c.mu.Unlock() to unlock it as the method is returning. ...