Mutexes, sync and the race detector
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
When channels are not the answer
Channels are great for handing work from one goroutine to another. But sometimes you simply have a piece of shared state, like a map of cached prices or a counter of requests, that many goroutines need to read and update. For that, Go gives you locks in the sync package.
A data race
A data race happens when two goroutines access the same variable at the same time and at least one of them writes. The result is unpredictable. Here is a program with a race:
var visits int
func main() {
var wg sync.WaitGroup
for range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
visits++ // read, add, write: three steps
}()
}
wg.Wait()
fmt.Println(visits) // often less than 1000
}
The statement visits++ looks like one step, but it is a read, an addition and a write. Two goroutines can read the same old value and both write back the same new one, losing an update. The answer changes from run to run, which makes this kind of bug very hard to catch by hand.
Fixing it with a mutex
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// SafeCounter is safe to use from many goroutines.
type SafeCounter struct {
mu sync.Mutex
counts map[string]int
}
func NewSafeCounter() *SafeCounter {
return &SafeCounter{counts: make(map[string]int)}
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counts[key]++
}
func (c *SafeCounter) Get(key string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.counts[key]
}
func main() {
counter := NewSafeCounter()
var total atomic.Int64
var wg sync.WaitGroup
for i := range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
if i%2 == 0 {
counter.Inc("even")
} else {
counter.Inc("odd")
}
total.Add(1)
}()
}
wg.Wait()
fmt.Println(counter.Get("even"), counter.Get("odd"), total.Load())
}
The output is always 500 500 1000.
How it works
A sync.Mutex lets only one goroutine hold the lock at a time. Lock() waits until the lock is free. Unlock() releases it. The code between them is the critical section. We write defer c.mu.Unlock() immediately after Lock(), so the lock is released on every path, including panics and early returns. Forgetting to unlock leads to a deadlock, where every other goroutine waits forever.
The mutex sits next to the data it protects, inside the same struct, and the only way to reach the data is through methods that take the lock. That keeps the locking in one place. The zero value of a Mutex is ready to use, so no setup is needed.
For a simple number, an atomic type is lighter than a mutex. atomic.Int64 offers Add, Load and Store as single, indivisible operations. Use atomics for counters and flags, and a mutex for anything involving more than one variable or a map.
RWMutex for read-heavy data
If many goroutines read and few write, sync.RWMutex allows any number of readers at once, but only one writer, who needs exclusive access. Readers call RLock() and RUnlock(), writers call Lock() and Unlock(). It is not always faster, since it has more overhead, so use it for caches where reads clearly dominate, and measure.
sync.Once
sync.Once runs a function exactly once, even if many goroutines ask at the same time. It is the right tool for lazy initialisation, such as loading configuration the first time it is needed.
var (
once sync.Once
config map[string]string
)
func getConfig() map[string]string {
once.Do(func() {
config = loadConfigFromDisk()
})
return config
}
The race detector
You do not need to find races by reading code. Go has a built-in detector. Add the -race flag:
go run -race .
go test -race ./...
go build -race
When two goroutines touch the same memory unsafely, it prints WARNING: DATA RACE with the stack traces of both accesses. It only finds races that actually happen during that run, so exercise the code with real concurrency, for example in tests with many goroutines. It slows the program down and uses more memory, so use it in tests and CI, not in production. I run go test -race on every project that starts a goroutine.
Common mistakes
- Copying a mutex. Passing a struct that contains a
sync.Mutexby value copies the lock. Use pointers.go vetflags this. - Locking twice in the same goroutine. A
sync.Mutexis not reentrant. If method A takes the lock and calls method B which also takes it, you deadlock. Split into a locked public method and an unlocked private helper. - Holding a lock while doing slow work like a network call. Everybody else waits. Copy what you need under the lock, release, then do the slow part.
- Protecting writes but not reads. A read without the lock is still a race.
- Returning a reference to protected data. If
Getreturned the internal map itself, callers could change it without the lock. Return a copy.
Try it yourself
Write a small in-memory cache type with Set(key, value string) and Get(key string) (string, bool), protected by a sync.RWMutex. Start 50 goroutines that write and 50 that read at the same time. First run it without locks using go run -race . and read the race report. Then add the locks and confirm that the warnings are gone.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
// SafeCounter is safe to use from many goroutines.
type SafeCounter struct {
mu sync.Mutex
counts map[string]int
}
func NewSafeCounter() *SafeCounter {
return &SafeCounter{counts: make(map[string]int)}
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.counts[key]++
}
func (c *SafeCounter) Get(key string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.counts[key]
}
func main() {
counter := NewSafeCounter()
var total atomic.Int64
var wg sync.WaitGroup
for i := range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
if i%2 == 0 {
counter.Inc("even")
} else {
counter.Inc("odd")
}
total.Add(1)
}()
}
wg.Wait()
fmt.Println(counter.Get("even"), counter.Get("odd"), total.Load())
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account