The Go memory model

The memory model is the set of guarantees about what one goroutine sees of another's writes. Without a synchronisation operation, there is no guarantee at all: the compiler may keep a value in a register, the CPU may reorder, and the race detector reports the pair. This lesson is the four operations that do give the guarantee, each as a program that prints the value it is allowed to rely on.

A send happens before a receive

The write to data happens before the send on done, and the send happens before the receive that takes the value, so the receive is ordered after the write and the read after the receive sees it. That chain is why the program prints ready and not an empty string: the model, not luck.

package main import "fmt" func main() { var data string done := make(chan bool) go func() { data = "ready" done <- true }() <-done fmt.Println("data:", data) }

go build -o app main.go && ./app

data: ready

The same rule covers a buffered channel with a twist: the receive that takes the value happens before the send that completes the buffer, so the k-th receive is ordered before the (k+1)-th send when the buffer is full. A close is also an ordering point: the close happens before a receive that returns the zero value because of it.

An unlock happens before a lock

A mutex gives the same guarantee through its two operations: an Unlock happens before a Lock that returns after it, so everything written before the unlock is visible after the lock. The program below writes under the lock and reads under it, and the done channel only orders the two goroutines, not the data.

package main import ( "fmt" "sync" ) func main() { var mu sync.Mutex var data string done := make(chan struct{}) go func() { mu.Lock() data = "locked" mu.Unlock() close(done) }() <-done mu.Lock() defer mu.Unlock() fmt.Println("data:", data) }

go build -o app main.go && ./app

data: locked

The read could also be ordered by the channel alone, since the close happens after the write and the receive after the close; the lock is there to show the pair. A mutex orders every write made before the unlock against every read after the lock, which is why a struct with several fields needs no atomic per field.

An atomic store publishes

An atomic store is not just a write that cannot tear: it orders the writes that came before it, and an atomic load that sees the value orders the reads after it. The pattern below publishes a whole immutable struct through a pointer, so a reader takes one atomic load and then reads the fields of a value nobody modifies.

package main import ( "fmt" "sync/atomic" ) type Config struct { Name string } func main() { var current atomic.Pointer[Config] done := make(chan struct{}) go func() { current.Store(&Config{Name: "v2"}) close(done) }() <-done fmt.Println("config:", current.Load().Name) }

go build -o app main.go && ./app

config: v2

The struct is immutable after the store, which is the second half of the rule: the atomic protects the pointer, not the fields, so a writer that modifies the pointed-to value after publishing it races with every reader. A configuration reload builds a new value and swaps the pointer, and an old value is collected when the last reader is done with it.

Happens-before is transitive

The relation composes. In the program below the first goroutine sends one, the second receives it, appends and sends one two, and main receives that. The send of the first channel is ordered before the receive, which is ordered before the second send, which is ordered before the last receive, so the whole chain is ordered even though it crosses three goroutines.

package main import "fmt" func main() { first := make(chan string) second := make(chan string) go func() { first <- "one" }() go func() { v := <-first second <- v + " two" }() fmt.Println("value:", <-second) }

go build -o app main.go && ./app

value: one two

The value travelled through two goroutines and arrived whole, and a write made before the first send would be visible after the last receive. That transitivity is why a pipeline of channels needs no extra lock between the stages, and why a channel is the simplest way to pass ownership of a value.

The rules of the model

The model names a short list of operations that establish happens-before: a send and the receive that takes it, a close and a receive that returns because of it, an unlock and a lock, a call to Once and the return of every other call, and an atomic operation and the atomic operation that observes it. A program with no such edge between a write and a read has a data race, and a data race is undefined behaviour, not a wrong value: the compiler and the CPU may do anything.

The practical rule: a value that crosses a goroutine boundary crosses it through a channel, a lock or an atomic, and a value that never crosses is a local. The race detector finds the pairs the model forbids, which is why the earlier lessons run their programs with -race; the next lesson measures what a value that escapes to the heap costs.

Exercises

  1. Replace the channel in the first program with a time.Sleep and run it under -race. Which pair does the detector report?
  2. Move the read in the mutex program outside the lock. Does the program still print the value, and what does the detector say?
  3. Publish a config, then modify a field of the same struct from the writer. Why is that a race even though the pointer is atomic?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is a data race?

    Answer

    Two accesses to one variable, at least one a write, with no happens-before edge

    Concurrency is fine; unsynchronised access is not.

  2. Which edge does a channel send create?

    Answer

    The send happens before the receive that takes the value

    That is why the write is visible after the receive.

  3. Which edge does a mutex create?

    Answer

    An unlock happens before a later lock

    Everything before the unlock is visible after the lock.

  4. What does an atomic store order?

    Answer

    The writes before it against the reads after the load that sees it

    That is how a config is published.

  5. Why must a published struct be immutable?

    Answer

    The atomic protects the pointer, not the fields

    A later write races with every reader.

  6. What does transitivity give a pipeline?

    Answer

    A write before the first send is visible after the last receive

    The edges compose.

  7. What happens in a program with a data race?

    Answer

    Undefined behaviour, not just a wrong value

    That is why the detector exists.

  8. Which operation is not a happens-before edge?

    Answer

    time.Sleep

    A sleep orders time, not memory.

  9. How does a value cross a goroutine boundary safely?

    Answer

    Through a channel, a lock or an atomic

    Those are the edges of the model.

  10. What finds a race the model forbids?

    Answer

    The race detector

    It instruments the accesses.

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