The memory model
The memory model says which writes a read can see. Each synchronizing operation creates an edge between goroutines. Without an edge, the compiler and the CPU owe you nothing, and these programs show it.
- 1A read sees a write only if an edge orders them. Time on a clock does not order anything.
- 2Two accesses race if one is a write, they have no order, and they are not all atomic.
- 3A racy program can see values that no goroutine wrote. It does not fail safely.
- 4The race detector finds races on code that ran. A clean run proves only that run.
// The flag is a plain bool. A goroutine sets it after 100 ms.
package main
import (
"fmt"
"os"
"time"
)
var done bool
func wait() {
if done {1
return
}
for !done {2
}
}
func main() {
go func() {
time.Sleep(100 * time.Millisecond)
done = true3
}()
time.AfterFunc(time.Second, func() {
fmt.Println("1 s later: done =", done, "and main still spins")
os.Exit(1)
})
wait()
fmt.Println("main saw done")
}- 1The first read of done.
- 2No goroutine may change done between these reads without an edge. So the compiler keeps the first value and spins on it.
- 3This write happens. The print proves it. The loop never reads memory again.
| flag | recorded output | status |
|---|---|---|
| bool | 1 s later: done = true and main still spins | Never ends, exit 1 from the timer |
| atomic.Bool | main saw done | Ends |
- The timer goroutine reads done as true. Main reads it as false, 900 ms after the write.
- This is a compiler result, on one CPU type and one Go version. The model allows it on all of them.
- The only change between the two programs is the type of the flag.
A plain flag is not a signal. With no edge, the compiler can reuse the first read forever. I use an atomic or a channel.
- Inside one goroutine, each step comes before the next.
- A synchronizing operation adds an edge from one goroutine to another.
- Follow the arrows. If a path joins two steps, they have an order.
- If no path joins them, they are concurrent, whatever the wall clock says.
Happens-before is a partial order. Inside a goroutine it follows the code. Across goroutines, only synchronizing operations add edges.
| two goroutines | verdict |
|---|---|
| Two goroutines write one int. Two writes with no order. | Race reported |
| One writes, one reads. One write is enough. | Race reported |
| Two goroutines read. A race needs a write. | No race |
| Each writes its own slice element. Elements are separate memory locations. | No race |
| Each writes its own struct field. Fields are separate memory locations. | No race |
| Both use atomics. Atomic accesses cannot race. | No race |
| One atomic write, one plain write. All accesses must be atomic. | Race reported |
| Both hold one mutex. Unlock orders the critical sections. | No race |
| Each holds a different mutex. Two mutexes give no order between them. | Race reported |
| One writes a map, one reads another key. A map is one data structure, not one location per key. | Race reported |
A data race is a write and another access to one location, with no order, unless all of them are atomic.
package main import ( "fmt" "time" ) var a string func main() { go func() { a = "hello" }() time.Sleep(10 * time.Millisecond) fmt.Println(a) }
step 1 of 4, clock [1, 0]
Inside one goroutine, each step comes after the previous step.
0 of 0 earlier steps happen before this one.
- selected step
- happens before it
- no order with it
- synchronizing edge
- data race
- Each program shows one schedule that really runs. Click a step, or step through it.
- A test runs each real program under the race detector and compares the verdict with this graph.
- Compare the unbuffered and buffered programs. The code differs by one number, and only one is correct.
I follow the arrows from the write to the read. If no path exists, the code has a race, even if it always prints the right value.
| operation | the edge | status |
|---|---|---|
| go f() | The go statement comes before the first step of f. | Edge |
| goroutine exit | No edge to anything. Use a WaitGroup or a channel. | No edge |
| ch <- v | A send comes before the completion of its receive. | Edge |
| close(ch) | A close comes before a receive that returns a zero value because of it. | Edge |
| <-ch, unbuffered | A receive comes before the matching send returns. | Edge |
| <-ch, capacity C | Receive number k comes before send number k+C returns. A semaphore uses this rule. | Not the first C sends |
| mu.Unlock() | Unlock number n comes before Lock number n+1 returns. | Edge |
| RWMutex | The same for Lock. RLock returns after the earlier Unlock, and RUnlock comes before the next Lock. | Edge |
| mu.TryLock() | A failed TryLock creates no edge. | Only when it succeeds |
| once.Do(f) | The return of f comes before the return of every Do. | Edge |
| sync/atomic | A store comes before a load that observes it. All atomics have one total order. | Only if the load sees it |
| wg.Done() | Done comes before the return of the Wait that it unblocks. | Edge |
| cond.Signal() | Signal comes before the Wait that it wakes returns. | Edge |
| sync.Map | A write comes before a read that observes it. | Only if the read sees it |
| pool.Put(x) | Put comes before the Get that returns x. | Only that x |
| time.Sleep | No edge. It changes the timing and nothing else. | No edge |
Tests pass a plain string through the go statement, channels, Mutex, Once, atomics, WaitGroup, Cond and sync.Map under -race. The other rows come from the documentation. See G11 for how each type works.
I can name the edge for each shared variable: which unlock, which send, which atomic store. If I cannot name it, I have a race.
// ViaGo: the go statement comes before the first step of the goroutine.
func ViaGo() string {
msg := "hello"1
out := make(chan string, 1)
go func() { out <- msg }()
return <-out
}
// ViaSend: a send comes before the completion of its receive.
func ViaSend() string {
var msg string
c := make(chan struct{}, 1)
go func() {
msg = "hello"
c <- struct{}{}2
}()
<-c
return msg
}
// ViaClose: a close comes before a receive that returns because of it.
func ViaClose() string {
var msg string
done := make(chan struct{})
go func() {
msg = "hello"
close(done)3
}()
<-done
return msg
}- 1This write comes before the go statement, so the goroutine sees it.
- 2The write to msg is above this line. The receive completes after it.
- 3A close wakes every receiver, so one close publishes to many goroutines.
Each plain value crosses the goroutine boundary on an edge, so no lock is needed for that one handoff.
// ViaMutex: the nth Unlock comes before the n+1th Lock returns.
func ViaMutex() string {
var mu sync.Mutex
var msg string
wrote := make(chan struct{})
go func() {
mu.Lock()
defer mu.Unlock()
msg = "hello"
close(wrote)1
}()
<-wrote
mu.Lock()
defer mu.Unlock()
return msg
}
// ViaOnce: the one run of f comes before every Do returns.
func ViaOnce() [2]string {
var once sync.Once
var msg string
var got [2]string
var wg sync.WaitGroup
for i := range got {
wg.Go(func() {
once.Do(func() { msg = "hello" })2
got[i] = msg
})
}
wg.Wait()
return got
}
// ViaAtomic: a store comes before the load that observes it.
func ViaAtomic() string {
var msg string
var ready atomic.Bool
go func() {
msg = "hello"
ready.Store(true)3
}()
for !ready.Load() {4
}
return msg
}- 1This channel only makes the goroutine run first. The mutex alone gives the order, not the first turn.
- 2Every caller gets the edge, also a caller that did not run f.
- 3A plain write above this store becomes visible to the load that sees true.
- 4A spin works but burns a CPU. A channel parks the goroutine. This loop only shows the edge.
An atomic orders what came before the store, not only the atomic value. That is why a flag can publish a whole struct.
| race on | size | what the model allows | recorded in 5 runs | status |
|---|---|---|---|---|
| A plain counter | 1 word | Each read sees some real write, so increments are lost. 8 goroutines add 100,000 each. | 207179, 218009, 218093, 227076, 237944 | Wrong total |
| An interface value | 2 words | The type word of one write with the data word of another. | torn read: cat method, name dog; torn read: dog method, name cat | Wrong method for the data |
| A slice value | 3 words | The pointer of one write with the length of another. | slice of 1 byte, len 1048576: index 4096 passes the bounds check | Bounds check defeated |
// An interface value is two words: a type and a pointer to data. One
// goroutine swaps it with no lock, and main calls a method on what it reads.
package main
import (
"fmt"
"sync/atomic"
)
type speaker interface{ say() string }
type cat struct{ name string }
type dog struct{ name string }
func (c *cat) say() string { return "cat method, name " + c.name }
func (d *dog) say() string { return "dog method, name " + d.name }
var (
shared speaker
writes atomic.Int64
)
func main() {
c, d := &cat{"cat"}, &dog{"dog"}
shared = c
go func() {
for {
if writes.Add(1)%2 == 01 {
shared = c
} else {
shared = d
}
}
}()
for range 500_000_000 {
s := shared.say()2
if s != "cat method, name cat" && s != "dog method, name dog" {
fmt.Println("torn read:", s)
return
}
}
fmt.Println("no torn value in 500,000,000 reads")
}- 1The atomic add is a fence on this CPU, so each store leaves the store buffer. Without it, these runs showed no tear.
- 2Two loads: the type word, then the data word. The writer can run between them.
// A slice value is three words. The reader can take the pointer of one
// slice and the length of another, and the bounds check uses that length.
package main
import (
"fmt"
"sync/atomic"
)
var (
shared []byte
writes atomic.Int64
)
func main() {
short := make([]byte, 1)
long := make([]byte, 1<<20)
shared = short
go func() {
for {
if writes.Add(1)%2 == 0 {
shared = short
} else {
shared = long
}
}
}()
for range 500_000_000 {
s := shared
if len(s) == len(long) && &s[0] == &short[0]1 {
fmt.Printf("slice of 1 byte, len %d: index 4096 passes the2 "+
"bounds check\n", len(s))
return
}
}
fmt.Println("no torn value in 500,000,000 reads")
}- 1The pointer is from the 1-byte slice, and the length is from the long slice.
- 2The bounds check trusts the length, so the program can read and write outside the array.
Here the two types have one layout, so the tear only gives a wrong answer. With different layouts, a method reads the data as the wrong type. Strings and maps have the same risk.
A word-sized race reads an old or a new value. A multiword race can read a mix, and then memory safety is gone.
// Double-checked locking with a plain flag. The first check takes no lock.
package main
import (
"fmt"
"sync"
)
type config struct{ port int }
var (
mu sync.Mutex
ready bool
cfg *config
)
func get() *config {
if ready { // first check: no lock
return cfg
}
mu.Lock()
defer mu.Unlock()
if !ready {
cfg = &config{port: 8080}
ready = true2
}
return cfg
}
func main() {
var wg sync.WaitGroup
wrong := 0
var count sync.Mutex
for range 64 {
wg.Go(func() {
if c := get(); c == nil || c.port != 8080 {
count.Lock()
defer count.Unlock()
wrong++
}
})
}
wg.Wait()
fmt.Println("wrong reads:", wrong)
}- 1No edge joins this read to the write under the lock.
- 2The memory model lets another goroutine see this store before it sees cfg.
==================
WARNING: DATA RACE
Write at 0x000010ac6e08 by goroutine 8:
main.get()
main.go:25 +0x10d
main.main.func1()
main.go:36 +0x32
Previous read at 0x000010ac6e08 by goroutine 7:
main.get()
main.go:18 +0x30
main.main.func1()
main.go:36 +0x32
Goroutine 8 (running) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
Goroutine 7 (running) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
==================- Without -race, the program printed "wrong reads: 0" on this CPU. The CPU keeps stores in order, so this bug needs a compiler or a weaker CPU.
- Arm64 keeps fewer orders. Do not rely on a test on a laptop.
- The detector reports the race although the output is right, because it checks the order, not the result.
The fast path of a hand-written double check reads a plain flag. Seeing the flag does not prove that I see the data.
// Lazy builds a value on first use. The fast path is one atomic load, and
// that load is what makes the first check safe: a reader that sees the
// pointer also sees everything the builder wrote before it stored the
// pointer. Prefer sync.OnceValue. Use this form only when a failed build
// must retry.
type Lazy[T any] struct {
value atomic.Pointer[T]1
mu sync.Mutex
build func() (T, error)
}
// NewLazy returns a Lazy that calls build until one call succeeds.
func NewLazy[T any](build func() (T, error)) *Lazy[T] {
return &Lazy[T]{build: build}
}
// Get returns the value, and builds it if no build has succeeded yet.
func (l *Lazy[T]) Get() (*T, error) {
if v := l.value.Load(); v != nil {
return v, nil
}
l.mu.Lock()3
defer l.mu.Unlock()
if v := l.value.Load(); v != nil {
return v, nil
}
v, err := l.build()
if err != nil {
return nil, err
}
l.value.Store(&v)2
return &v, nil
}- 1The first check is now an atomic load, so it can observe the store.
- 2Everything build wrote comes before this store. A load that sees the pointer sees all of it.
- 3The mutex makes one builder at a time. The atomic carries the edge to readers.
I use sync.OnceValue. If a failed build must retry, I keep a double check with an atomic pointer for the first read.
| practice | status |
|---|---|
| One goroutine owns the data | Approved |
| One mutex guards each field | Approved |
| Build, then publish, then never write | Approved |
| A plain bool as a stop flag | Not approved |
| A sleep to wait for a goroutine | Not approved |
| "This word is small, so it is safe" | Not approved |
| Publish with an atomic, then write | Not approved |
I name the rule for each shared variable: owned by one goroutine, guarded by this mutex, or immutable after publish.
| situation | result | status |
|---|---|---|
| Two accesses ran with no edge | Report with both stacks, and exit code 66 when the program ends | Found |
| Correct output, wrong order (panel I) | Reported. It checks the order, not the output | Found |
| The racy path did not run (panel N) | Exit 0, output "hits: 0". With the path taken: exit 66 | Missed |
| This schedule added an edge by luck (panel M) | Exit 0 on one schedule, exit 66 on the other | Only on some schedules |
| Every access is locked, but the logic is wrong | No race exists to report. See G13 | Missed |
| Deadlocks and leaked goroutines | Not a data race. See G13 | Missed |
| Old history | The race report can say "failed to restore the stack". Raise GORACE history_size | Report loses a stack |
Halt on the first race with GORACE="halt_on_error=1". By default, the program prints each report and runs on. Cost: see panel R.
The race detector reports only what it saw, and it sees only what ran. So I run it under real load as well as in tests.
// One program, two schedules. The mutex guards nothing here, but it can
// add an edge between the write and the read if the writer unlocks first.
package main
import (
"fmt"
"os"
"sync"
"time"
)
var (
mu sync.Mutex
x int
)
func writer() {
x = 11
mu.Lock()
defer mu.Unlock()3
}
func reader() int {
mu.Lock()
mu.Unlock()
return x2
}
func main() {
writerDelay, readerDelay := time.Duration(0), 20*time.Millisecond
if os.Args[1] == "reader-first" {
writerDelay, readerDelay = readerDelay, writerDelay
}
var wg sync.WaitGroup
wg.Go(func() {
time.Sleep(writerDelay)
writer()
})
wg.Go(func() {
time.Sleep(readerDelay)
fmt.Println("read", reader())
})
wg.Wait()
}- 1Outside the mutex. This access has no guard.
- 2Also outside the mutex.
- 3If the writer unlocks first, the reader's Lock takes an edge from this Unlock. That edge orders the two accesses.
| schedule | printed | exit |
|---|---|---|
| Writer first | read 1 | 0 |
| Reader first | read 0 | 66 |
==================
WARNING: DATA RACE
Write at1 0x000005ab5ea8 by goroutine 7:
main.writer()
main.go:18 +0x27
main.main.func1()
main.go:38 +0x33
Previous read at2 0x000005ab5ea8 by goroutine 8:
main.reader()
main.go:27 +0x3c
main.main.func2()
main.go:42 +0x33
Goroutine 7 (running) created at:3
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
Goroutine 8 (finished) created at:
sync.(*WaitGroup).Go()
$GOROOT/src/sync/waitgroup.go:238 +0x72
==================- 1The access that the detector caught last.
- 2The earlier access in its history. Fix the pair, not one line.
- 3Where the goroutine began. The goroutine number differs on each run.
A mutex that guards nothing can still hide a race on a good schedule, because the detector sees the edge that this run made.
// A race on a path that runs only with an argument.
package main
import (
"fmt"
"os"
"sync"
)
func main() {
hits := 0
var wg sync.WaitGroup
wg.Go(func() {
if len(os.Args) > 1 {
hits++1
}
})
wg.Go(func() {
if len(os.Args) > 1 {
hits++
}
})
wg.Wait()
fmt.Println("hits:", hits)
}- 1A real race, on a path that needs an input the test did not give.
| run | printed | exit | status |
|---|---|---|---|
| No argument | hits: 0 | 0 | Clean, and the race is still there |
| One argument | Found 1 data race(s) | 66 | Found |
The detector sees executed code only, so race coverage equals test coverage. I add concurrent tests for each shared path.
| since | what changed | what it means here |
|---|---|---|
| 1.19 | The memory model was revised to match C, C++, Java, JavaScript, Rust and Swift. Go has sequentially consistent atomics only. New types: atomic.Int64, atomic.Pointer[T] and others. | No relaxed forms to choose from. A typed atomic cannot be read by accident with a plain load. |
| 1.21 | sync.OnceFunc, OnceValue and OnceValues. | Replaces most hand-written double checks. |
| 1.22 | Each iteration of a for loop creates new variables. | A closure no longer shares the loop variable. Vet stops the old report for files at 1.22 or later. |
| 1.25 | sync.WaitGroup.Go. Vet reports a misplaced WaitGroup.Add. The race detector supports linux/loong64. | The late Add from the drill cannot happen with wg.Go. |
| 1.26 | The race detector supports linux/riscv64. | One more server target can run -race. |
Go 1.27 has no memory model change and no race detector change in its release notes.
| when | the moment | what to do or say |
|---|---|---|
| build | A handler reads a map that another handler writes. | Guard it now. A read counts: one write plus any read is a race. |
| build | A background goroutine must stop. | Use ctx.Done, not a plain bool. Panel A shows why. |
| build | You add a concurrency test. | Run with -race, and make goroutines overlap on real work. The detector only sees what ran. |
| talk | "Is reading an int without a lock safe?" | No. The result is some real value, but the compiler can reuse it forever, and the program has a race. |
| talk | "Why not double-checked locking?" | Seeing the flag does not order the data. Use sync.OnceValue, or an atomic pointer. |
| talk | "What does -race miss?" | Paths that did not run, logic races under correct locks, deadlocks and leaks. |
| talk | "Do you run -race in production?" | In a canary, at most. It costs about 7.5 times the time and 4.0 times the memory here. |
I never argue from timing. I name the edge, and I run the tests with -race.
0 of 10 known
Predict the output.
package main import "fmt" var a string func main() { c := make(chan int, 10) go func() { a = "hello" c <- 0 }() <-c fmt.Printf("%q\n", a) }Predict the output.
package main import "fmt" var a string func main() { c := make(chan int, 10) go func() { a = "hello" close(c) }() v, ok := <-c fmt.Printf("%d %v %q\n", v, ok, a) }Predict the output. The receive is in the goroutine.
package main import "fmt" var a string func main() { c := make(chan int) go func() { a = "hello" <-c }() c <- 0 fmt.Printf("%q\n", a) }Predict the output. The goroutine unlocks a mutex that main locked.
package main import ( "fmt" "sync" ) var ( mu sync.Mutex a string ) func main() { mu.Lock() go func() { a = "hello" mu.Unlock() }() mu.Lock() fmt.Printf("%q\n", a) }Predict the output.
package main import ( "fmt" "sync" ) var ( once sync.Once a string runs int ) func setup() { runs++ a = "hello" } func main() { var wg sync.WaitGroup got := make([]string, 8) for i := range got { wg.Go(func() { once.Do(setup) got[i] = a }) } wg.Wait() fmt.Println(runs, got) }Predict the output.
package main import ( "fmt" "sync/atomic" ) var ( a string ready atomic.Bool ) func main() { go func() { a = "hello" ready.Store(true) }() for !ready.Load() { } fmt.Printf("%q\n", a) }Predict the output.
package main import ( "fmt" "sync" "sync/atomic" ) func main() { var n atomic.Int64 var wg sync.WaitGroup for range 8 { wg.Go(func() { for range 100_000 { n.Add(1) } }) } wg.Wait() fmt.Println(n.Load()) }Predict the output.
package main import ( "fmt" "sync" "sync/atomic" "time" ) func main() { limit := make(chan struct{}, 3) var now, peak atomic.Int64 var wg sync.WaitGroup for range 40 { wg.Go(func() { limit <- struct{}{} n := now.Add(1) for { p := peak.Load() if n <= p || peak.CompareAndSwap(p, n) { break } } time.Sleep(time.Millisecond) now.Add(-1) <-limit }) } wg.Wait() fmt.Println("peak:", peak.Load()) }Predict the output. The goroutines sleep before they call Add.
package main import ( "fmt" "sync" "time" ) func main() { var wg sync.WaitGroup var mu sync.Mutex total := 0 for range 3 { go func() { time.Sleep(5 * time.Millisecond) wg.Add(1) defer wg.Done() mu.Lock() defer mu.Unlock() total++ }() } wg.Wait() mu.Lock() defer mu.Unlock() fmt.Println("total:", total) }Predict the output. Only the type of the flag changed from panel A.
// The flag is an atomic.Bool. Nothing else changed. package main import ( "fmt" "os" "sync/atomic" "time" ) var done atomic.Bool func wait() { if done.Load() { return } for !done.Load() { } } func main() { go func() { time.Sleep(100 * time.Millisecond) done.Store(true) }() time.AfterFunc(time.Second, func() { fmt.Println("1 s later: done =", done.Load(), "and main still spins") os.Exit(1) }) wait() fmt.Println("main saw done") }
- load
- 1.1 ns plain; 1.1 ns atomic.
- store
- 1.4 ns plain; 5.8 ns atomic.
- mutex
- 11.4 ns alone.
- -race
- 7.5 times the time and 4.0 times the memory on one workload here. Documentation says 2 to 20 and 5 to 10.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs. An atomic load on this CPU is a plain load that the compiler must not remove. Use these as orders of magnitude.