sync.Mutex
sync.Mutex is a mutual-exclusion lock. Lock waits until the mutex is free, then takes it. Unlock releases it. Only one goroutine holds the lock at a time.
Detailed Explanation
Two goroutines incrementing n++ without a lock is a data race: both read, both write, one increment is lost. mu.Lock(); n++; mu.Unlock() makes the increment a critical section. The mutex does not protect the integer by magic; it protects whatever you access while holding it. Every read and write of n must use the same mutex.
Zero value is unlocked. var mu sync.Mutex is ready. Do not copy a mutex after first use; put it in a struct and pass the struct by pointer.
defer mu.Unlock() next to Lock. That is the defer story: early returns still unlock. Do not hold a lock across a slow I/O call if other goroutines need it — copy the data out, unlock, then I/O.
Not reentrant. The same goroutine calling Lock twice without Unlock deadlocks. There is no Lock count. If you need to call a method that also locks, split an unlocked inner function.
TryLock. Since Go 1.18, TryLock returns false instead of waiting. Use it for "do this only if you can get the lock now," not as a substitute for a correct lock order.
What it costs. An uncontended Lock/Unlock is a few atomic operations. A contended mutex parks goroutines. Fine-grained locks (one per shard) reduce contention and increase deadlock risk. Start with one mutex around the struct, measure, then shard.
Code Examples
package main
import "sync"
type counter struct {
mu sync.Mutex
n int
}
func (c *counter) Inc() {
c.mu.Lock()
defer c.mu.Unlock()
c.n++
}
func (c *counter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.n
}
func main() {
var c counter
c.Inc()
_ = c.Value()
}func (c *counter) IncUnlocked() { // caller must hold c.mu
c.n++
}Common Gotchas
Copying a struct that contains a mutex copies the lock
embed and pass pointers.
Reading `n` without the lock is still a race
both sides of the protocol must lock.
Unlock of an unlocked mutex panics
Unlock of an unlocked mutex panics
Mutex is not held across `Unlock`; there is no "upgrade" to RWMutex in place
Mutex is not held across `Unlock`; there is no "upgrade" to RWMutex in place