Mutexes allow safe access of state across multiple goroutines. If one goroutine is r/w to a var, other goroutines are mutually excluded from accessing it.
var m = &sync.Mutex{}
mutexes can be embedded in structs:
type currency struct {
sync.Mutex
amount float64
}
func (c *currency) Add(i float64) {
c.Lock()
c.amount += i
c.Unlock()
}
defer c.Unlock()
is useful if a function contains multiple return statementssnyc.RWMutex
, with m.RLock()
and m.RUnlock()