Explain it simply
Synchronization in plain language
Goroutines let work happen at the same time. The trouble starts when several of them read and change the same variable. If two goroutines read the old value at the same moment and each writes back its own increment, one update simply disappears. That is called a data race.
Think of a single bathroom with a lock. Only one person can be inside, and everyone else waits until the lock is released. sync.Mutex is that lock. Put the code that touches shared data between Lock and Unlock, and only one goroutine at a time can be inside it.
Problem → Why → Solution
The problem: a counter that is only sometimes wrong
Say you want to count requests to a website. Each request runs in its own goroutine and bumps a shared counter with counter++. On your laptop it prints 1000, the next run prints 987, and on the CI server it prints 941. There is no compile error and no panic; the bug is completely silent.
package main
import (
"fmt"
"sync"
)
func main() {
counter := 0
var wg sync.WaitGroup
for range 1000 {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // DATA RACE: read, add, write are three separate steps
}()
}
wg.Wait()
fmt.Println(counter) // often less than 1000
}Why counter++ is not safe
counter++ is one line, but for the CPU it is three steps: read from memory, add one, write back. If two goroutines both read 41, both write 42 and an increment is lost. Beyond that, the Go memory model gives no guarantees about a program with an unsynchronized race, so you should not treat it as 'only slightly off'.
Core concept: every piece of shared data needs one rule
A data race needs three things at once: two or more goroutines touch the same memory location, at least one of them writes, and nothing synchronizes them. Remove any one of the three and the race is gone. You can let one goroutine own the data and pass it over channels (no sharing), only read it after setup (no writes), or use a lock (add synchronization).
sync.Mutex is the most common tool. mu.Lock() takes the lock and waits if another goroutine holds it; mu.Unlock() releases it. The code between them is called the critical section. Write defer mu.Unlock() right after locking, so the lock is released on every return path. The standard Go shape is to keep the mutex in the same struct as the fields it guards and only touch them through pointer-receiver methods. A mutex must never be copied, because the copy is a separate lock.
For a single value such as a counter or a flag, the sync/atomic package is lighter. Add, Load, Store and CompareAndSwap on atomic.Int64 are indivisible at the hardware level. But atomic protects one value at a time; a rule that spans two fields or two steps, like 'check the balance, then subtract', needs a mutex. sync.WaitGroup protects no data at all: it waits for goroutines to finish, and guarantees that once Wait() returns, everything they wrote is visible.
sync.RWMutex has two kinds of lock. RLock lets many readers in at once, while Lock waits until every reader has left and then admits a single writer. It only pays off when reads dominate and the critical sections are not tiny; for short ones a plain Mutex is simpler and often faster.
| Tool | Use it when |
|---|---|
| sync.Mutex | a map, slice or several fields change together |
| sync.RWMutex | reads vastly outnumber writes |
| atomic.Int64 / atomic.Bool | a single counter or flag |
| Channel | one goroutine owns the data and others send it messages |
| sync.WaitGroup | waiting until a group of goroutines finishes |
- Find the data goroutines share
- Pick one owner or one lock
- Lock, then defer Unlock
- Read results only after Wait()
A lock does not protect data by itself; code that takes the lock before touching the data does. A single access that skips the lock brings the race back.
General pattern
type SafeThing struct {
mu sync.Mutex
field Type // guarded by mu
}
func (s *SafeThing) Update(v Type) {
s.mu.Lock()
defer s.mu.Unlock()
// read and write s.field here
}
var hits atomic.Int64 // hits.Add(1), hits.Load()Keep the mutex in the struct next to the fields it guards, and pair Lock with defer Unlock inside pointer-receiver methods. For one standalone value, an atomic type is enough.
Worked example: 300 goroutines updating one inventory
In the program below, 300 goroutines bump apple, banana and cherry stock at the same time. A mutex guards the map, and an atomic counter counts the requests. The keys are sorted before printing so the output is identical on every run, even though map iteration order is random.
package main
import (
"fmt"
"sort"
"sync"
"sync/atomic"
)
// Inventory is safe for concurrent use: mu guards stock.
type Inventory struct {
mu sync.Mutex
stock map[string]int
}
func (inv *Inventory) Add(item string, n int) {
inv.mu.Lock()
defer inv.mu.Unlock()
inv.stock[item] += n
}
func (inv *Inventory) Snapshot() map[string]int {
inv.mu.Lock()
defer inv.mu.Unlock()
out := make(map[string]int, len(inv.stock))
for k, v := range inv.stock {
out[k] = v
}
return out
}
func main() {
inv := &Inventory{stock: map[string]int{}}
var requests atomic.Int64
var wg sync.WaitGroup
items := []string{"apple", "banana", "cherry"}
for i := range 300 {
wg.Add(1)
go func() {
defer wg.Done()
inv.Add(items[i%len(items)], 1)
requests.Add(1)
}()
}
wg.Wait()
snap := inv.Snapshot()
names := make([]string, 0, len(snap))
for name := range snap {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
fmt.Printf("%s: %d\n", name, snap[name])
}
fmt.Println("requests:", requests.Load())
}Code breakdown
- Mutex next to the data
mu sync.MutexThe mutex lives in the same struct as the stock map. A zero-value Mutex is an unlocked, ready-to-use lock, so no constructor is needed.
- Lock with defer Unlock
defer inv.mu.Unlock()Unlock is deferred right after Lock, so the lock is always released once the map update finishes. Writing a map concurrently without a lock can make the Go runtime stop the program with a 'concurrent map writes' fatal error.
- Copy before sharing
for k, v := range inv.stock {Snapshot copies the entries into a new map while holding the lock. Returning the real map would let callers read it without the lock and bring the race back.
- Atomic counter
requests.Add(1)requests is an atomic.Int64, so Add is one indivisible operation. A single number needs no mutex.
- Wait before reading
wg.Wait()Only after Wait() returns have all 300 goroutines finished and all of their writes become visible. Reading before that would give a half-finished result.
apple: 100
banana: 100
cherry: 100
requests: 300Running the race detector
Racy code usually prints the right answer, so you cannot find races by looking at output. Go ships a race detector behind the -race flag. It watches every memory access while the program runs and, when it sees two unsynchronized accesses, reports the stack traces of both goroutines. On most platforms it needs cgo and a C compiler.
go run -race racy_counter.go # run one program with detection on
go test -race ./... # run every test in the module with detection onRunning the counter from the problem section with -race produces a report like the one below. Addresses, goroutine numbers and line numbers vary between runs, so treat this as an abridged sample. When a race is found, the program exits with status 66.
==================
WARNING: DATA RACE
Read at 0x00c000014108 by goroutine 8:
main.main.func1()
/home/you/racy_counter.go:15 +0x84
Previous write at 0x00c000014108 by goroutine 7:
main.main.func1()
/home/you/racy_counter.go:15 +0x96
==================
Found 1 data race(s)
exit status 66No report does not mean no race
The detector only checks code paths that actually run. If your tests never exercise the concurrent path, the race goes unreported. It also slows the program down and uses more memory, so it is usually turned on for tests and staging rather than production.
In real projects
Where this shows up in real Go services
An HTTP server is a concurrent program: net/http runs each request in its own goroutine. So any package-level map, cache or counter that handlers share can race from the day it goes live. It usually hides during low-load local testing and appears only under real traffic.
- In-memory caches: a map[string]Item guarded by sync.RWMutex, with RLock for Get and Lock for Set.
- Metrics: request and error counts kept in atomic.Int64 values that a /metrics endpoint reads with Load.
- Rate limiters and connection pools have a 'check, then take' rule, so both steps happen under one mutex.
- Many teams put go test -race ./... in their CI pipeline and treat any race report as a failing test.
Common mistakes
Common synchronization mistakes
Copying a struct that contains a mutex
A value receiver like func (c Counter) Inc() copies the struct on every call, so both the lock and the data change on a copy and the real object never changes. Use a pointer receiver, (c *Counter). The copylocks check in go vet catches this.
Calling wg.Add inside the goroutine
With go func() { wg.Add(1); ... }(), main can reach wg.Wait() before the goroutine starts, see a zero counter and return at once. Call wg.Add(1) before the go statement. Go 1.25 and later also offer wg.Go(f), which pairs Add and Done for you.
Mixing atomic and plain access, or locking two steps separately
Writing a variable atomically in one place and reading it plainly somewhere else is still a race. Similarly, reading Balance() under the lock and then calling Withdraw() under a separate lock makes each step safe, yet another goroutine can withdraw in between. Do the check and the change under one lock.
Best practices
Best practices
- Place the fields a mutex guards right below it and add a '// guarded by mu' comment.
- Keep critical sections short; never make a network call or sleep while holding a lock.
- Return a copy instead of an internal map or slice.
- Write a test that exercises every concurrent path and run it with -race in CI.
Mini challenge
Mini challenge: a bank account that cannot go negative
Write an Account type that many goroutines can withdraw from at once. Starting with a balance of 500, 100 goroutines each withdraw 10. Every run must end with exactly 50 successes, 50 rejections and a balance of 0.
- Account holds a sync.Mutex and a balance field
- Withdraw checks and subtracts under one lock and returns ErrInsufficientFunds when money is short
- Count successes and rejections with atomic.Int64
- Print the three results only after wg.Wait()
package main
import (
"errors"
"fmt"
"sync"
"sync/atomic"
)
var ErrInsufficientFunds = errors.New("insufficient funds")
type Account struct {
// TODO: a mutex and the balance it guards
}
func (a *Account) Deposit(amount int) {
// TODO: lock, add, unlock
}
func (a *Account) Withdraw(amount int) error {
// TODO: check AND subtract while holding the lock
return nil
}
func (a *Account) Balance() int {
// TODO: read the balance under the lock
return 0
}
func main() {
acct := &Account{}
acct.Deposit(500)
var ok, rejected atomic.Int64
var wg sync.WaitGroup
// TODO: start 100 goroutines that each withdraw 10 and count the outcome
wg.Wait()
fmt.Println(ok.Load(), rejected.Load(), acct.Balance())
}Expected: Every run prints succeeded: 50, rejected: 50, balance: 0. Which goroutines succeed can differ between runs, but the counts never change.
Show hint
Make the first two lines of Withdraw a.mu.Lock() and defer a.mu.Unlock(), then check if a.balance < amount. Inside each goroutine, use errors.Is(err, ErrInsufficientFunds) to tell the outcomes apart.
Show solution
package main
import (
"errors"
"fmt"
"sync"
"sync/atomic"
)
var ErrInsufficientFunds = errors.New("insufficient funds")
type Account struct {
mu sync.Mutex
balance int // guarded by mu
}
func (a *Account) Deposit(amount int) {
a.mu.Lock()
defer a.mu.Unlock()
a.balance += amount
}
// Withdraw checks and updates under ONE lock, so two goroutines
// cannot both see enough money and both take it.
func (a *Account) Withdraw(amount int) error {
a.mu.Lock()
defer a.mu.Unlock()
if a.balance < amount {
return ErrInsufficientFunds
}
a.balance -= amount
return nil
}
func (a *Account) Balance() int {
a.mu.Lock()
defer a.mu.Unlock()
return a.balance
}
func main() {
acct := &Account{}
acct.Deposit(500)
var ok, rejected atomic.Int64
var wg sync.WaitGroup
for range 100 {
wg.Add(1)
go func() {
defer wg.Done()
if err := acct.Withdraw(10); errors.Is(err, ErrInsufficientFunds) {
rejected.Add(1)
} else {
ok.Add(1)
}
}()
}
wg.Wait()
fmt.Println("succeeded:", ok.Load())
fmt.Println("rejected:", rejected.Load())
fmt.Println("balance:", acct.Balance())
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A data race happens when two goroutines touch the same memory without synchronization and one of them writes.
- Use sync.Mutex for maps and multi-field state, and write defer Unlock right after Lock.
- Use atomic.Int64 for a lone counter and sync.WaitGroup to wait for goroutines to finish.
- go test -race finds races on the paths your tests exercise, so run it in CI.
Data Race Detector — Go