A mutex (short for Mutual Exclusion) is a lock used to restrict multiple goroutines from accessing a resource (critical section) to prevent race conditions from occurring.

Mutexes involve locking and unlocking a resource. In the example below, they’re used to synchronise access to the counters field.

type Container struct {
    mu       sync.Mutex
    counters map[string]int
}
 
func (c *Container) inc(name string) {
 
    c.mu.Lock()
    defer c.mu.Unlock()
    c.counters[name]++
}
 
....