Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 147 ยท Concurrency

Data Races and the Memory Model

Learn what a Go data race is, why counter++ loses updates, how mutexes, atomics and channels fix it, the happens-before rules of the memory model and how to use go run -race.

Goroutines are cheap and easy to start, and that is exactly why concurrency bugs are easy to write. The most common one is the data race: two goroutines touch the same variable at the same time, at least one of them writes, and nothing orders the accesses. The program may work a thousand times and then print a wrong total on the thousand-and-first run, or crash only on your customer's machine.

This lesson explains what a race really is, shows the lost-update problem step by step, and then fixes it with the tools from the previous lessons: a mutex, an atomic and a channel. After that you learn the rules of Go's memory model, the short list of guarantees that tell you when one goroutine is allowed to see what another one wrote, and you meet the usual suspects: maps, slices, loop variables and shared error variables.

What a data race is

A data race needs all of these conditions:

  1. Two or more goroutines access the same memory location.
  2. At least one of the accesses is a write.
  3. The accesses are not ordered by synchronization (a lock, a channel operation, an atomic operation, and so on).

Two goroutines that only read a variable never race. Two goroutines that write different variables never race. Goroutines that take turns through a mutex never race. Remove any one condition and the problem disappears; that is how every fix in this lesson works.

Here is the classic example. Many goroutines add one to a shared counter, with nothing to protect it. This is read-only, because its output is different on every run and may be correct by luck:

Go
package main

import (
	"fmt"
	"sync"
)

func main() {
	var wg sync.WaitGroup
	counter := 0

	for range 1000 {
		wg.Go(func() {
			counter++ // DATA RACE: read, add, write with no synchronization
		})
	}

	wg.Wait()
	fmt.Println(counter) // often less than 1000
}

The wg.Go method (Go 1.25) starts a goroutine and does the Add/Done bookkeeping for you, as shown in goroutines. The race is the counter++ line.

Why counter++ loses updates

counter++ looks like one operation, but the machine performs three: load the value, add one, store the result. Two goroutines can interleave those steps. Both load 0, both compute 1, both store 1, and one increment is gone.

You can see the lost update deterministically by playing both goroutines yourself in one function, step by step, in the order the unlucky schedule would use:

Go The lost update, step by step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Two increments happened, yet the counter is 1. With thousands of goroutines on several cores, this kind of overlap happens constantly, which is why the racy loop above loses a different number of updates every time.

A data race is not just "a slightly wrong number". The Go memory model gives racy programs no useful guarantees. Values can be torn, stale or reordered, and a race on a multi-word value such as an interface, a slice or a string header can corrupt memory. Treat every race as a bug that must be removed, never as something you can live with.

Fix 1: protect the data with a mutex

A sync.Mutex allows one goroutine at a time into a critical section. Everything between Lock and Unlock runs without interference, so the load-add-store sequence can no longer interleave:

Go Fixing the counter with a mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output is always counter: 1000. Notice that Value takes the lock too: reads must be synchronized as well, because a read that overlaps a write is still a race. Keeping the mutex next to the data it protects, in the same struct, and never exporting the field, is the standard way to make the rule hard to break.

Fix 2: use an atomic

For one simple number, an atomic operation is lighter than a mutex. The sync/atomic package performs the whole read-modify-write as one indivisible step:

Go Fixing the counter with an atomic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Again 1000 every time. Atomics are ideal for counters, flags and statistics. As soon as two variables must change together (say a balance and a transaction count), an atomic per variable is not enough, and you need a mutex around both. The atomics lesson covers that boundary.

Fix 3: let one goroutine own the data

The third fix removes condition 1 instead: only one goroutine ever touches the variable, and everybody else sends it requests through a channel. This is the idea behind the Go proverb "Do not communicate by sharing memory; instead, share memory by communicating."

Go One owner goroutine, many senders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The variable total is local to the owner goroutine, so no other goroutine can reach it, and the channel operations carry the data safely between goroutines. Closing increments after wg.Wait() is safe because every sender has finished by then.

Which fix should you pick? A short guide:

Situation Good choice
One counter or flag atomic.Int64, atomic.Bool
A struct or map with several fields to protect sync.Mutex (or RWMutex for read-heavy data)
A stream of work, or state that one component naturally owns A channel and an owner goroutine
Data that never changes after creation Nothing: immutable data is safe to share

Finding races with the race detector

You do not have to find races by staring at code. Go ships a race detector. Add -race to the build, run or test command, and the compiled program watches every memory access at run time:

Terminal
go run -race main.go
go test -race ./...
go build -race -o app-race .

On your machine, running the racy counter from the beginning of this lesson with -race prints a report like this (paths, addresses and counts will differ):

TEXT
==================
WARNING: DATA RACE
Read at 0x00c000012120 by goroutine 8:
  main.main.func1()
      /home/you/race/main.go:14 +0x34

Previous write at 0x00c000012120 by goroutine 7:
  main.main.func1()
      /home/you/race/main.go:14 +0x44

Goroutine 8 (running) created at:
  main.main()
      /home/you/race/main.go:13 +0x7c
==================
Found 1 data race(s)
exit status 66

Each report tells you which two accesses collided, the line of each, and where the goroutines were created. The detector exits with status 66 so that CI fails. A few facts to remember:

  • It reports only races that actually happen during the run. A clean run does not prove the program is race-free, so run your tests with -race often, and exercise concurrent paths.
  • It makes programs roughly 5 to 10 times slower and use more memory, so you use it in tests and staging, not in production builds.
  • It needs cgo and a supported platform, which is why this site's runner (a static, cgo-free build) cannot demonstrate it. Run the commands above on your own computer.

The Go memory model: happens-before

If two goroutines use a variable, when is a read guaranteed to see an earlier write? The Go memory model answers with one idea, happens-before. If event A happens before event B, then B is guaranteed to see everything A did. If neither happens before the other, the two events are concurrent, and if they touch the same memory, one writing, you have a data race.

Inside a single goroutine, statements happen in program order. Between goroutines, the order exists only where the language or the library creates it. These are the rules you will use every day:

Synchronizing event What happens before what
go f() The go statement happens before f starts running
Channel send A send happens before the matching receive completes
Channel close close(ch) happens before a receive that returns because the channel is closed
Unbuffered receive A receive happens before the matching send completes
Buffered channel (capacity C) The k-th receive happens before the (k+C)-th send completes
Mutex / RWMutex The n-th Unlock happens before the (n+1)-th Lock returns
sync.Once The single call of f happens before any Do(f) returns
WaitGroup Each Done happens before the Wait it releases returns
sync/atomic An atomic write that is observed by an atomic read happens before that read returns

Notice what is not on the list: time.Sleep, a long delay, or the fact that your goroutine "surely started by now". Sleeping orders nothing, so code that relies on it is racy even if it passes every test on your laptop.

Publishing data with a channel

The send-before-receive rule is how you hand a finished value from one goroutine to another. Everything written before the send is visible after the receive:

Go Channel close publishes earlier writes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

There is no mutex and no atomic, and still no race, because close(ready) happens before the receive returns. The same pattern works with wg.Wait(): every write made before a goroutine's Done is visible after Wait returns, which is why the results[i] = ... slots in the goroutines lesson were safe to read at the end.

Sleeping is not synchronization

A wrong program often looks like the following. This one is read-only, because the point is that it is broken even when it appears to work:

Go
var ready bool
var message string

func setup() {
	message = "hello"
	ready = true
}

func main() {
	go setup()
	for !ready { // RACE: nothing orders this read after the writes
	}
	fmt.Println(message) // might print an empty string
}

The compiler may hoist the read of ready out of the loop, so it spins forever. Even without that optimization, the processor may make ready = true visible before message = "hello". A channel, a mutex, or atomic.Bool for ready fixes it. In Go there is no such thing as a "benign" race on shared variables.

Common races to watch for

Maps

Maps are not safe for concurrent use. Reading while another goroutine writes, or two goroutines writing, is a race, and the runtime often catches it and kills the program with fatal error: concurrent map writes or fatal error: concurrent map read and map write. That check is best effort and not guaranteed, so never depend on it. Put a mutex next to the map:

Go A map protected by a mutex

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

After wg.Wait() it is safe to read the map without the lock, because Wait ordered all the writes before it. Printing in sorted order keeps the output stable, since map iteration order is random (see maps).

Slices and append

Writing to different elements of a slice from different goroutines is fine, as in the results[i] example. But append changes the slice header (its length, and maybe its backing array), so concurrent append calls to one shared slice are a race and can silently drop items. Protect the append with a mutex, or give each goroutine its own slot:

Go Collecting results without a race

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

We sort the result because the goroutines finish in an unpredictable order. If the order matters, preallocate make([]int, n) and let goroutine i write only squares[i], which needs no lock.

Loop variables and shared variables

Before Go 1.22, all iterations of a for loop shared one loop variable, and goroutines started in the loop raced on it. Since Go 1.22 each iteration has its own copy, which removed a whole class of bugs (see for loops). Variables declared outside the loop are still shared, so this is still a race:

Go
var err error
for _, url := range urls {
	wg.Go(func() {
		err = fetch(url) // RACE: every goroutine writes the one shared err
	})
}

Give each goroutine its own variable (err := fetch(url) inside the closure) and send it back through a channel or a per-goroutine slot.

Other frequent sources: copying a struct that contains a sync.Mutex (the copy has its own lock, so nothing is protected, and go vet reports it), reading a struct field while another goroutine runs a method that changes it, and lazily initializing a global without sync.Once.

A checklist for every piece of shared data: Who writes it? Who reads it? What orders those accesses? If you cannot answer the third question in one sentence ("the mutex", "the channel", "it is never changed after startup"), you have a race.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which situation is a data race?

    A race needs the same memory, at least one write and no synchronization. Only the third option has all three. Reads alone, different elements and a shared mutex are all safe.
  2. 2. Two goroutines run counter++ on a shared int with no protection. What can happen?

    counter++ is a load, an add and a store. Interleaved, two increments can produce one. The program compiles and usually does not panic, which is what makes the bug so easy to miss.
  3. 3. Which of these creates a happens-before relationship?

    A channel send happens before the matching receive completes. Sleeping, start order and spinning on a plain variable order nothing.
  4. 4. What does go run -race main.go do?

    The race detector watches memory accesses at run time and reports races it observes. A clean run does not prove absence of races, and the instrumentation makes the program slower.
  5. 5. Many goroutines add to a shared map[string]int. What is the correct fix?

    Maps are not safe for concurrent writes, and concurrent reads while writing are also a race. A mutex (or sync.Map, or a single owner goroutine) fixes it. Sleeping and capacity do not.

Summary

  • A data race is two or more goroutines accessing the same memory, at least one writing, with no synchronization between them. Races have no safe or benign form in Go.
  • counter++ is load, add, store, so unsynchronized goroutines lose updates.
  • Fix a race by adding synchronization: a sync.Mutex around the data, an sync/atomic type for a single value, or a channel and one owner goroutine. Immutable data needs no protection.
  • The memory model is built on happens-before. Channel sends and closes, mutex unlock and lock, WaitGroup Done and Wait, sync.Once, atomics and the go statement create it. Sleeping does not.
  • Maps and shared append calls need a lock. Writing to separate slice elements is safe. Loop variables are per-iteration since Go 1.22, but variables declared outside the loop are still shared.
  • Run tests with go test -race ./.... The detector finds races that happen during the run, so a clean report is encouraging but not a proof.

Next: Time, Timers and Tickers covers measuring, formatting and scheduling time in Go.