Lesson 36 of 38 · Concurrency
Go Mutex: Protecting Shared State with sync.Mutex
Channels are great for passing data from one goroutine to another, but sometimes many goroutines simply need to update the same thing — a counter, a cache, a scoreboard. Doing that safely requires a lock, and Go's sync package has one: the mutex.
Data races
A data race happens when two goroutines access the same variable at the same time and at least one of them writes. Even hits++ is not one step: the CPU loads hits, adds one and stores the result. Two goroutines can both load 41, both compute 42 and both store 42 — one increment is lost. Here, 1000 goroutines increment a shared counter once each:
var hits int
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
hits++ // data race!
}()
}
wg.Wait()
fmt.Println(hits)
One run printed:
969
On a multi-core machine the result is often below 1000 and changes from run to run. In this browser runtime all goroutines take turns on a single thread, so you may well see 1000 — the bug is still there, just hidden. Real Go has a race detector that reports such bugs: go run -race or go test -race. Concurrent writes to a map are even worse: Go detects them and crashes with fatal error: concurrent map writes.
sync.Mutex
A mutex (mutual exclusion lock) lets only one goroutine at a time into a critical section:
var (
mu sync.Mutex
hits int
)
func hit() {
mu.Lock() // wait until no other goroutine holds the lock
defer mu.Unlock() // release it when the function returns
hits++
}
Lock blocks while another goroutine holds the mutex; Unlock releases it. Writing defer mu.Unlock() right after Lock guarantees the unlock on every return path. With the mutex, a thousand goroutines calling hit always end at exactly 1000.
A mutex inside a struct
The mutex usually lives right next to the data it protects:
type Inventory struct {
mu sync.Mutex
items map[string]int
}
func (inv *Inventory) Add(item string, n int) {
inv.mu.Lock()
defer inv.mu.Unlock()
inv.items[item] += n
}
The methods use pointer receivers, and the struct is passed around as *Inventory. Never copy a mutex: a copy is a separate lock, so two copies protect nothing — go vet warns about it (passes lock by value). The zero value of sync.Mutex is an unlocked mutex, ready to use, but the map still has to be created with make.
RWMutex and atomic counters
When data is read much more often than it is written, a sync.RWMutex lets many readers in at once: readers call RLock/RUnlock, writers call Lock/Unlock and get exclusive access.
For a single number, the sync/atomic package is simpler and faster:
var hits atomic.Int64
hits.Add(1) // safe from any goroutine
fmt.Println(hits.Load()) // read it safely
Channels or mutexes?
Use channels to pass data and ownership between goroutines or to signal events: work items, results, "done". Use a mutex to guard state that several goroutines share: a cache, a counter, a scoreboard. Pick whichever keeps the code simpler — real programs often use both.
Common mistakes
- Forgetting to unlock on an early return: the next
Lockwaits forever. Usedefer. - Locking twice in the same goroutine: Go's mutex is not re-entrant, so a method that holds the lock must not call another method that locks it again.
- Value receivers such as
func (c Counter) Inc(): each call locks a copy of the mutex and changes a copy of the data. - Reading without the lock: reads race with writes too. Protect every access, not just the writes.
- Returning the protected map: the caller could then use it without the lock. Return a copy.
Assignment
Build a counter that many goroutines can use at once. SafeCounter holds a mutex and a map[string]int:
NewSafeCounter() *SafeCounterreturns a ready-to-use counter, with its map created.(c *SafeCounter) Inc(key string)adds 1 to the count ofkey.(c *SafeCounter) Value(key string) intreturns the current count ofkey(0for unknown keys).(c *SafeCounter) Snapshot() map[string]intreturns a copy of all counts: changing the returned map must not change the counter.
All methods must be safe to call from many goroutines at the same time. Keep the mu field: one test locks c.mu itself to check that your methods really wait for the mutex.
c := NewSafeCounter()
c.Inc("gold")
c.Inc("gold")
c.Inc("gems")
c.Value("gold") // 2
c.Snapshot() // map[gems:1 gold:2]Premium lesson
Unlock the full Learn Go course
- All 38 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.
Lesson last updated on .