sync.Mutex and shared state
Two goroutines that touch the same variable without coordination have a data race: the result depends on timing, and the compiler and the CPU are allowed to assume there is none. Go offers no atomic keyword at the language level, so the fix is a sync.Mutex or the sync/atomic package. This lesson takes the counter apart and puts it back together.
A counter that loses updates
A thousand goroutines increment one int and the program waits for all of them. The total should be a thousand and it is not: total++ is a read, an add and a write, and two goroutines can read the same value before either writes, so one increment overwrites the other. The output changes from run to run, and a race can be invisible for months.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
total := 0
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
total++
}()
}
wg.Wait()
fmt.Println("total:", total)
}
go build -o app main.go && ./app
total: 987
Thirteen increments disappeared. The count is not the point: the same program can print 1000 on a quiet machine and 940 on a busy one, and a test that checks the total will pass and fail at random. A number that is sometimes right is the signature of a race.
What the race detector says
The race detector is a compiler instrumentation that records every memory access and reports the pairs that are not ordered by a synchronisation operation. Build with -race and run: the report names both accesses, both goroutines and the lines that created them. The program below has exactly one read and one write of x and no lock, so it is reported every time.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
x := 0
wg.Add(2)
go func() {
defer wg.Done()
x++
}()
go func() {
defer wg.Done()
fmt.Println("read:", x)
}()
wg.Wait()
fmt.Println("x:", x)
}
go build -trimpath -race -o app-race main.go && ./app-race
==================
WARNING: DATA RACE
Read at 0x00c0000180e8 by goroutine 9:
main.main.func2()
main.go:20 +0xc4
Previous write at 0x00c0000180e8 by goroutine 8:
main.main.func1()
main.go:15 +0x8d
Goroutine 9 (running) created at:
main.main()
main.go:18 +0x1c8
Goroutine 8 (finished) created at:
main.main()
main.go:13 +0x126
==================
read: 1
x: 1
Found 1 data race(s)
exit status: 66
The report says which access came first, which goroutine made each one and where both were created. The address and the offsets change between runs and machines, and the read may print 0 or 1: the detector proves the race, not a particular outcome. Exit status 66 is the detector's own, so a test run with -race fails even when the test itself passes.
A mutex around the counter
sync.Mutex has two methods, Lock and Unlock, and one rule: every Lock is followed by exactly one Unlock on every path. A defer mu.Unlock() right after the Lock is the shape that survives a panic and an early return. With the lock, the read, the add and the write are one step that no other goroutine can enter.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var mu sync.Mutex
total := 0
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
defer mu.Unlock()
total++
}()
}
wg.Wait()
fmt.Println("total:", total)
}
go build -o app main.go && ./app
total: 1000
go build -trimpath -race -o app-race main.go && ./app-race
total: 1000
The run under -race printed the correct total and no report: the lock orders every increment, and the detector can see that order. The price is that a thousand goroutines now wait for one another; a mutex is the right tool when the critical section is short, and the wrong tool around a slow call such as a network request.
RWMutex
A sync.RWMutex lets any number of readers in at once and a writer alone. The counter below reads its value often and increments it less often, so RLock and RUnlock around the read let the readers proceed in parallel while Lock still excludes everyone. A writer waits for the readers, and readers that keep arriving can delay a writer; the runtime gives a waiting writer priority, which is why a busy read path does not starve it.
package main
import (
"fmt"
"sync"
)
type Counter struct {
mu sync.RWMutex
n int
}
func (c *Counter) Add() {
c.mu.Lock()
defer c.mu.Unlock()
c.n++
}
func (c *Counter) Value() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.n
}
func main() {
var wg sync.WaitGroup
c := &Counter{}
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
c.Add()
_ = c.Value()
}()
}
wg.Wait()
fmt.Println("value:", c.Value())
}
go build -o app main.go && ./app
value: 100
The mutex lives inside the struct, so a copy of the Counter copies the lock, which vet reports as a copied lock. The methods take a pointer receiver, the struct is never copied, and the zero value of the mutex is ready to use: no constructor and no init function are needed.
Exercises
- Run the losing counter ten times and collect the totals. What is the spread, and what does it say about how often the race happens?
- Move the defer wg.Done() after the lock in the mutex version. Does the program still pass the detector, and what would happen to a second goroutine?
- Replace the mutex with atomic.Int64 and compare the time of a million increments. Which version is faster, and which is easier to read?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a data race?
Answer
Two goroutines accessing the same variable without synchronisation, one writing
Concurrency is fine; unsynchronised access is the race.
-
Why does total++ lose updates?
Answer
It is a read, an add and a write that another goroutine can interleave with
Two reads of the same value produce one increment.
-
Which flag builds a program with the race detector?
Answer
-race
It instruments every memory access.
-
What does the race detector report?
Answer
Both accesses, both goroutines and where they were created
The report is a pair of stacks around the two accesses.
-
What exit status does a race cause?
Answer
66
That is how the detector fails a CI run.
-
What is the rule of Lock and Unlock?
Answer
Every Lock has exactly one Unlock on every path
A defer right after Lock is the safe shape.
-
What does RWMutex allow?
Answer
Any number of readers or one writer
Readers share, a writer is exclusive.
-
Why does vet complain about a copied Counter with a mutex?
Answer
The copied lock protects a different variable
A copied mutex is a different mutex.
-
When is a mutex the wrong tool?
Answer
Around a slow network call that would serialise every goroutine
A long critical section turns concurrency back into a queue.
-
What is the zero value of sync.Mutex?
Answer
An unlocked mutex ready to use
A struct with a mutex field needs no constructor.
The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev