Chapter 0 · Section 4 of 8 · 3 min read
In Go
Goroutines in one paragraph
A goroutine is a function running concurrently with the code that started it. You start one by putting the word go in front of a function call. The program does not wait for it. To wait, you need something that coordinates the two, and the standard choice is sync.WaitGroup.
The counter in Go
Here is the whole demonstration. Counter.Inc is our three steps with the gap made explicit, and Run starts several goroutines that all call Inc.
// Package lostupdate shows the smallest concurrency bug: several goroutines
// adding to one number with nothing coordinating them.
package lostupdate
import (
"runtime"
"sync"
"sync/atomic"
)
// Incrementer is anything that can be incremented and read back.
type Incrementer interface {
Inc()
Value() int
}
// Counter is a plain counter. Inc is three steps (read, add, write), and
// nothing stops another goroutine from running between them. The call to
// runtime.Gosched makes the gap between the read and the write easy to hit, so
// the bug shows up on every run instead of once in a million.
type Counter struct{ n int }
// Inc adds one to the counter. It is NOT safe to call from several goroutines.
func (c *Counter) Inc() {
v := c.n // read
runtime.Gosched()
c.n = v + 1 // write
}
// Value returns the current count.
func (c *Counter) Value() int { return c.n }
// AtomicCounter does the same job with one indivisible step. Chapter 12 covers
// atomic operations properly; it is here so you can compare.
type AtomicCounter struct{ n atomic.Int64 }
// Inc adds one to the counter. It is safe to call from several goroutines.
func (c *AtomicCounter) Inc() { c.n.Add(1) }
// Value returns the current count.
func (c *AtomicCounter) Value() int { return int(c.n.Load()) }
// Run starts workers goroutines that each call Inc perWorker times, waits for
// all of them, and returns the final value.
func Run(c Incrementer, workers, perWorker int) int {
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := 0; j < perWorker; j++ {
c.Inc()
}
}()
}
wg.Wait()
return c.Value()
}A few things to notice:
Counterhas no lock and no atomics. It is the code from the problem section.Inccallsruntime.Gosched()between the read and the write. That asks the scheduler to let another goroutine run. I added it so the gap is wide enough to hit reliably on any machine. On my machine the loss is large even without it. I ran a copy with a plaincount++five times, 8 goroutines adding 1000 times each, and got 6038, 4465, 4693, 4313 and 5405 out of 8000.Runuses async.WaitGroupto wait for every goroutine to finish before it reads the result.
Run it
go run ./chapters/00-why-concurrency-is-hard/code/cmd/demoTwo runs on my machine (Go 1.25.2, Apple silicon) printed:
expected 8000, got 1011 (6989 updates lost)
expected 8000, got 1291 (6709 updates lost)Your numbers will differ. They will almost never be 8000.
The race detector
You do not have to guess whether a program races. Go ships a detector. From the Go documentation:
To help diagnose such bugs, Go includes a built-in data race detector. To use it, add the
-raceflag to the go command.Source: Data Race Detector, go.dev.
It works with go test -race, go run -race, go build -race and go install -race. Run the same program with it:
go run -race ./chapters/00-why-concurrency-is-hard/code/cmd/demoHere is the start of the report, with file paths shortened:
==================
WARNING: DATA RACE
Read at 0x00c0000ae018 by goroutine 11:
.../code.(*Counter).Inc()
.../lostupdate.go:25 +0x2c
.../code.Run.func1()
.../lostupdate.go:52 +0xa0
Previous write at 0x00c0000ae018 by goroutine 7:
.../code.(*Counter).Inc()
.../lostupdate.go:27 +0x44
.../code.Run.func1()
.../lostupdate.go:52 +0xa0
Goroutine 11 (running) created at:
.../code.Run()
.../lostupdate.go:49 +0x60Read it like a sentence. A read at the address of n by goroutine 11, at line 25, conflicts with an earlier write to the same address by goroutine 7, at line 27. Line 25 is v := c.n and line 27 is c.n = v + 1. It also tells you where each goroutine was created. That is usually enough to find the bug.
The tests in this chapter
The package has three tests. Each shows something different.
| Test | How to run it | What it shows |
|---|---|---|
TestAtomicCounterKeepsEveryUpdate | go test -race ./chapters/00-why-concurrency-is-hard/code | A fix using one indivisible step passes, even under -race. |
TestPlainCounterLosesUpdates | go test ./chapters/00-why-concurrency-is-hard/code | Without the detector, the plain counter ends below the target. The file has the build tag !race, so it is left out when -race is on. |
TestPlainCounterIsRacy | go test -race -tags raceDemo ./chapters/00-why-concurrency-is-hard/code | With the detector, the same code fails with WARNING: DATA RACE. The raceDemo tag keeps this deliberate failure out of the normal test run. |
The repository's continuous integration runs the first, and checks that the third really fails.
One way to fix it, for now
AtomicCounter replaces the three steps with a single operation that the hardware performs as one unit:
type AtomicCounter struct{ n atomic.Int64 }
func (c *AtomicCounter) Inc() { c.n.Add(1) }It passes the race detector and keeps every update. Chapter 12 explains how atomic operations work and where they stop being enough. In Chapter 1 you will meet the tool that works for any amount of code, not only a single number: the mutex.