Go Mutex
Channels are great for passing data between goroutines. But sometimes several goroutines simply need to update one shared variable — a counter, a cache, a map of sessions. For that, Go provides the mutex (mutual exclusion lock) in the sync package.
The problem: a data race
count++ looks like a single step, but it is really three: read the value, add one, write it back. If two goroutines interleave those steps, increments get lost:
var count int
for range 1000 {
go func() { count++ }() // DATA RACE: unpredictable result
}The final count could be 1000, 973, 991… it changes between runs. Running with go run -race reports WARNING: DATA RACE.
sync.Mutex
A sync.Mutex has two methods: Lock and Unlock. Only one goroutine can hold the lock at a time; others calling Lock wait until it is released. The code between them is called the critical section.
package main
import (
"fmt"
"sync"
)
func main() {
var (
mu sync.Mutex
count int
wg sync.WaitGroup
)
for range 1000 {
wg.Go(func() {
mu.Lock()
count++ // only one goroutine at a time gets here
mu.Unlock()
})
}
wg.Wait()
fmt.Println("count:", count)
}count: 1000
Protecting a struct
The idiomatic way is to put the mutex inside the struct next to the data it guards, and to use pointer receivers so the mutex is never copied. defer mu.Unlock() right after Lock guarantees the lock is released on every path.
package main
import (
"fmt"
"slices"
"sync"
)
type Inventory struct {
mu sync.Mutex
stock map[string]int
}
func NewInventory() *Inventory {
return &Inventory{stock: make(map[string]int)}
}
func (inv *Inventory) Add(item string, qty int) {
inv.mu.Lock()
defer inv.mu.Unlock()
inv.stock[item] += qty
}
func (inv *Inventory) Report() []string {
inv.mu.Lock()
defer inv.mu.Unlock()
var lines []string
for item, qty := range inv.stock {
lines = append(lines, fmt.Sprintf("%s: %d", item, qty))
}
slices.Sort(lines)
return lines
}
func main() {
inv := NewInventory()
var wg sync.WaitGroup
deliveries := []string{"apples", "pears", "apples", "plums", "apples", "pears"}
for _, item := range deliveries {
wg.Go(func() {
inv.Add(item, 10)
})
}
wg.Wait()
for _, line := range inv.Report() {
fmt.Println(line)
}
}apples: 30
pears: 20
plums: 10
Note: Go maps are not safe for concurrent writes. Writing to a map from several goroutines without a lock can crash the program with
fatal error: concurrent map writes.
sync.RWMutex: many readers, one writer
When reads are far more common than writes, a sync.RWMutex lets any number of readers hold the lock together (RLock/RUnlock), while a writer (Lock/Unlock) gets exclusive access.
package main
import (
"fmt"
"sync"
)
type Config struct {
mu sync.RWMutex
data map[string]string
}
func (c *Config) Get(key string) string {
c.mu.RLock()
defer c.mu.RUnlock()
return c.data[key]
}
func (c *Config) Set(key, value string) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = value
}
func main() {
cfg := &Config{data: map[string]string{"theme": "dark"}}
var wg sync.WaitGroup
reads := make([]string, 5)
for i := range reads {
wg.Go(func() {
reads[i] = cfg.Get("theme") // readers run in parallel
})
}
wg.Wait()
fmt.Println(reads)
cfg.Set("theme", "light")
fmt.Println(cfg.Get("theme"))
}[dark dark dark dark dark]
light
Atomic counters
For a single number, the sync/atomic package is simpler and faster than a mutex:
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var visits atomic.Int64
var wg sync.WaitGroup
for range 500 {
wg.Go(func() {
visits.Add(1)
})
}
wg.Wait()
fmt.Println("visits:", visits.Load())
}visits: 500
Mutex or channel?
| Use a mutex when… | Use a channel when… |
|---|---|
| goroutines share state (a cache, a counter, a map) | goroutines hand data to each other |
| the critical section is short | you need to signal events or completion |
| you're guarding a struct's internals | you're building a pipeline or worker pool |
Tip: Keep critical sections small. Never do slow work (network calls, disk I/O) while holding a lock, and never call
Locktwice from the same goroutine — Go mutexes are not re-entrant, so that deadlocks.
Test yourself
Why is count++ from many goroutines unsafe without synchronisation?
++is not allowed in goroutines- It is a read-modify-write that can interleave and lose updates
- Integers are immutable
- It is safe
What does sync.RWMutex allow that sync.Mutex does not?
- Multiple simultaneous writers
- Multiple simultaneous readers
- Locking twice from the same goroutine
- Automatic unlocking
Why write defer mu.Unlock() right after mu.Lock()?
- It is faster
- It guarantees the lock is released on every return path, even on panic
- It is required by the compiler
- It makes the lock re-entrant