These are the notes for Go episode 46. In episode 45 a race condition lost rotis, and we noticed only because the number was obviously wrong. Now Raju takes orders on the app and the phone, two goroutines each adding one, and the program prints the right answer, 2, every time. The race is still there. You meet the race detector (-race), learn to read its report, and see its one blind spot (it only checks code that runs). Then the Go memory model: why a plain bool flag between goroutines gives no guarantee, the happens-before relation, which operations synchronise goroutines, why no race is benign (a real program where the compiler removed racy writes), what -race costs, and running go test -race in CI.
All outputs and errors here are from real runs (Go 1.25.1, linux/amd64, a machine with 2 CPUs). Memory addresses, goroutine numbers, timings and counts change from run to run.
Facts and sources
- Data Race Detector (Go docs):
- "A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write."
- "To use it, add the
-raceflag to the go command":go test -race mypkg,go run -race mysrc.go,go build -race mycmd,go install -race mypkg. - "The race detector only finds races that happen at runtime, so it can't find races in code paths that are not executed. If your tests have incomplete coverage, you may find more races by running a binary built with
-raceunder a realistic workload." - "The cost of race detection varies by program, but for a typical program, memory usage may increase by 5-10x and execution time by 2-20x."
- Supported:
linux/amd64,linux/ppc64le,linux/arm64,linux/s390x,linux/loong64,freebsd/amd64,netbsd/amd64,darwin/amd64,darwin/arm64,windows/amd64. GORACEoptions includeexitcode(default66),halt_on_error(default0) andlog_path(defaultstderr).- The Go Memory Model, "Version of June 6, 2022":
- Advice: "Programs that modify data being simultaneously accessed by multiple goroutines must serialize such access." "If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever."
- "The happens before relation is defined as the transitive closure of the union of the sequenced before and synchronized before relations."
- Channels: "A send on a channel is synchronized before the completion of the corresponding receive from that channel." "The closing of a channel is synchronized before a receive that returns a zero value because the channel is closed." "A receive from an unbuffered channel is synchronized before the completion of the corresponding send on that channel."
- Locks: "For any sync.Mutex or sync.RWMutex variable l and n < m, call n of l.Unlock() is synchronized before call m of l.Lock() returns."
- Once: "The completion of a single call of f() from once.Do(f) is synchronized before the return of any call of once.Do(f)."
- Atomics: "If the effect of an atomic operation A is observed by atomic operation B, then A is synchronized before B."
- DRF-SC: "In the absence of data races, Go programs behave as if all the goroutines were multiplexed onto a single processor."
- The busy-wait example (
for !done {}thenprint(a)): "there is no guarantee that, in main, observing the write to done implies observing the write to a, so this program could print an empty string too. Worse, there is no guarantee that the write to done will ever be observed by main … The loop in main is not guaranteed to finish." - Multiword values: "races on multiword data structures can lead to inconsistent values not corresponding to a single write. When the values depend on the consistency of internal (pointer, length) or (pointer, type) pairs, as can be the case for interface values, maps, slices, and strings in most Go implementations, such races can in turn lead to arbitrary memory corruption."
- "Implementations using ThreadSanitizer (accessed with "go build -race") do exactly this": report the race and halt.
The problem: a race that looks fine
| In Raju's kitchen | In Go |
|---|---|
| the app takes an order and adds 1 to the register | goroutine 1: orders++ |
| the phone takes an order and adds 1 to the same register | goroutine 2: orders++ |
| the register says 2 every time you check | the program prints 2 |
| the busy day when both write at the same instant | a lost update, rarely |
A data race: two goroutines access the same variable concurrently (nothing forces one access to finish before the other starts), and at least one access is a write.
go run -race
The race detector is a tool built into the Go toolchain. A program built with the -race flag records every memory access and every synchronising operation while it runs, and reports accesses from different goroutines that are not ordered by any synchronisation.
// files: go.mod (module shop, go 1.25) and main.go
// commands: go run . then go run -race .
package main
import (
"fmt"
"sync"
)
func main() {
orders := 0 // today's order count
var wg sync.WaitGroup
wg.Go(func() { orders++ }) // the app counts one order
wg.Go(func() { orders++ }) // the phone counts one order
wg.Wait()
fmt.Println("orders today:", orders)
}
Real output:
$ go run .
orders today: 2
$ go run -race .
orders today: 2
==================
WARNING: DATA RACE
Read at 0x00c000012118 by goroutine 8:
main.main.func1()
main.go:11 +0x2e
sync.(*WaitGroup).Go.func1()
/usr/local/go1.25.1/src/sync/waitgroup.go:239 +0x5d
Previous write at 0x00c000012118 by goroutine 9:
main.main.func2()
main.go:12 +0x44
sync.(*WaitGroup).Go.func1()
/usr/local/go1.25.1/src/sync/waitgroup.go:239 +0x5d
Goroutine 8 (running) created at:
sync.(*WaitGroup).Go()
/usr/local/go1.25.1/src/sync/waitgroup.go:237 +0x86
main.main()
main.go:11 +0xde
Goroutine 9 (finished) created at:
sync.(*WaitGroup).Go()
/usr/local/go1.25.1/src/sync/waitgroup.go:237 +0x86
main.main()
main.go:12 +0x149
==================
Found 1 data race(s)
exit status 66
Both runs print the right answer. Only -race shows the bug. The detector doesn't need the race to cause a wrong result, or even to happen at the exact same instant: it sees that the two accesses are not ordered by any synchronisation.
The first -race run of a program is slower to start, because the standard library is rebuilt with race instrumentation (in our session the very first run took about 11 s; later runs about 1 s).
Reading a race report
| Part of the report | What it tells you |
|---|---|
Read at 0x00c000012118 by goroutine 8: + stack |
one access: its kind (read/write), the memory address of the variable, which goroutine, and the call stack (your line: main.go:11) |
Previous write at 0x00c000012118 by goroutine 9: + stack |
the other access it clashes with. Same address = same variable |
Goroutine 8 (running) created at: |
where each goroutine was started, to find it in a big program |
Found 1 data race(s) |
the count at exit |
exit status 66 |
a program with a detected race exits with code 66 (change it with GORACE=exitcode=N), so scripts and CI see a failure |
- A memory address is the number that says where a variable lives in memory (episode 11).
- Goroutines are numbered as they are created; the numbers mean nothing else.
- Lines inside
/usr/local/go…/src/are Go's own code (hereWaitGroup.Gostarting your function); look for your files. GORACE=halt_on_error=1stops at the first race instead of continuing.
The fix
package main
import (
"fmt"
"sync"
)
func main() {
orders := 0
var mu sync.Mutex
var wg sync.WaitGroup
add := func() { mu.Lock(); orders++; mu.Unlock() }
wg.Go(add) // the app
wg.Go(add) // the phone
wg.Wait()
fmt.Println("orders today:", orders)
}
Real output:
$ go run -race .
orders today: 2
No report. "No report" means no race was seen in this run, not "no race exists", as the next program shows.
The blind spot: only code that runs
// commands: go run -race . then go run -race . rush
package main
import (
"fmt"
"os"
"sync"
)
func main() {
rush := len(os.Args) > 1 && os.Args[1] == "rush"
orders := 0
var mu sync.Mutex
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Go(func() {
if rush {
orders++ // the rush-hour shortcut: no lock
return
}
mu.Lock()
orders++
mu.Unlock()
})
}
wg.Wait()
fmt.Println("rush:", rush, " orders:", orders)
}
Real output (shortened):
$ go run -race .
rush: false orders: 2
$ go run -race . rush
rush: true orders: 2
==================
WARNING: DATA RACE
Read at 0x00c000112020 by goroutine 8:
main.main.func1()
main.go:17 +0x48
...
Previous write at 0x00c000112020 by goroutine 9:
main.main.func1()
main.go:17 +0x5a
...
Found 1 data race(s)
exit status 66
os.Args holds the program's command-line arguments (episode 18). The racy branch (line 17) is found only when it runs. So: tests must exercise every concurrent path, ideally with realistic load, and a staging server running a -race build under real traffic finds more.
Visibility across goroutines
Visibility is the question: when one goroutine writes a variable, when is another goroutine guaranteed to see the new value, and in which order does it see several writes?
// commands: go run . then go run -race .
package main
import (
"fmt"
"time"
)
var slip string // the order slip
var done bool // "the slip is ready"
func raju() {
time.Sleep(10 * time.Millisecond) // writing takes a moment
slip = "2 masala dosa"
done = true
}
func main() {
go raju()
for !done { // the cook keeps checking the flag
}
fmt.Println("cooking:", slip)
}
Real output (shortened):
$ go run .
cooking: 2 masala dosa
$ go run -race .
cooking: 2 masala dosa
==================
WARNING: DATA RACE
Write at 0x00000060fcc8 by goroutine 8:
main.raju()
main.go:14 +0x6d
Previous read at 0x00000060fcc8 by main goroutine:
main.main()
main.go:19 +0x33
...
==================
==================
WARNING: DATA RACE
Read at 0x0000005efb60 by main goroutine:
main.main()
main.go:21 +0x76
Previous write at 0x0000005efb60 by goroutine 8:
main.raju()
main.go:13 +0x30
...
==================
Found 2 data race(s)
exit status 66
Two races: on done (lines 14 and 19) and on slip (lines 13 and 21). It "worked", but the Go memory model, which uses this exact example, says:
- seeing done == true does not guarantee seeing the write to slip, so it could print an empty string;
- there is no guarantee main ever sees done change at all: "The loop in main is not guaranteed to finish".
The compiler and the CPU may reorder or remove memory operations as long as a single goroutine can't tell the difference. Without synchronisation, another goroutine can.
Happens-before and synchronising operations
The Go memory model is the official document that says which writes a read is guaranteed to see.
| In Raju's kitchen | Memory model term | Meaning |
|---|---|---|
| Raju writes the slip, then rings the bell, in that order | sequenced before | the order of statements inside one goroutine |
| the cook hears that bell, then reads | synchronized before | a link between two goroutines, made by a synchronising operation |
| so writing certainly comes before reading | happens before | chains of the two above; a write that happens before a read is guaranteed to be visible to it |
Synchronising operations (the "bells"):
| Operation | Rule (simplified) | Episode |
|---|---|---|
mu.Unlock() → next mu.Lock() |
the Unlock is synchronized before the next Lock returns | 45 |
wg.Done() → wg.Wait() returning |
everything before Done is visible after Wait | 45 |
| channel send → its receive completes | a send is synchronized before the receive completes | 47 |
| unbuffered receive → its send completes | the receive is synchronized before the send completes | 47 |
close(ch) → a receive that sees "closed" |
the close is synchronized before that receive | 47 |
once.Do(f) |
f's completion is synchronized before any Do returns | 50 |
atomic operations (sync/atomic) |
an observed atomic write is synchronized before the read | 50 |
the go statement |
the go statement is synchronized before the new goroutine starts |
43 |
A plain variable read or write (done = true, for !done) is not a synchronising operation.
If two accesses to the same variable are not ordered by happens-before and one is a write, that's a data race, and the guarantees are gone. If a program has no data races, it behaves as if the goroutines simply took turns on one CPU (DRF-SC: data-race-free programs are sequentially consistent).
The fix: a real bell
package main
import (
"fmt"
"sync"
"time"
)
var slip string // the order slip
func raju() {
time.Sleep(10 * time.Millisecond)
slip = "2 masala dosa"
}
func main() {
var wg sync.WaitGroup
wg.Go(raju) // Done happens when raju returns...
wg.Wait() // ...and is synchronized before Wait returns
fmt.Println("cooking:", slip)
}
Real output:
$ go run -race .
cooking: 2 masala dosa
Chain: slip = … is sequenced before raju's Done → Done is synchronized before Wait returns → Wait is sequenced before Println(slip). So the write happens before the read: guaranteed, not lucky. The done flag is gone completely. (A channel, episode 47, or an atomic.Bool, episode 50, would also work.)
The memory model's own advice: "Don't be clever." Use a mutex, a WaitGroup or a channel rather than reasoning about orderings yourself.
Why "benign" races are not benign
A benign race is a race people believe is harmless ("only one writer", "an old value is fine", "it's just statistics"). Go has no such thing.
package main
import (
"fmt"
"time"
)
type Menu struct{ Dosa, Idli, Chai int }
var oldMenu = Menu{60, 40, 10}
var newMenu = Menu{70, 50, 15}
var board = oldMenu // the price board everyone reads
func main() {
go func() { // the owner keeps switching the board
for i := 0; ; i++ {
if i%2 == 0 {
board = newMenu
} else {
board = oldMenu
}
}
}()
sawNew, mixed := 0, 0
start := time.Now()
for time.Since(start) < 300*time.Millisecond {
m := board // "only reading, what can go wrong?"
if m == newMenu {
sawNew++
} else if m != oldMenu {
mixed++
}
}
fmt.Println("saw the new menu:", sawNew, "times")
fmt.Println("saw a mixed-up menu:", mixed, "times")
}
Real output (every run):
saw the new menu: 0 times
saw a mixed-up menu: 0 times
The reader never saw the new menu. Why? We looked at the machine code the compiler made, with go build -gcflags=-S board.go (-S prints the assembly):
main.main.func1 STEXT nosplit size=3 args=0x0 locals=0x0 funcid=0x0 align=0x0
... (board.go:16) XCHGL AX, AX
... (board.go:1) JMP 0
The owner's goroutine compiled to a 3-byte empty infinite loop (JMP 0 jumps back to itself). The writes to board were removed: the loop never ends and contains no synchronisation, so within that goroutine nothing can ever observe the writes, and the compiler may drop them. That is a legal optimisation for a racy program.
The same program with one mutex around the write and the read:
mu.Lock()
if i%2 == 0 {
board = newMenu
} else {
board = oldMenu
}
mu.Unlock()
...
mu.Lock()
m := board // read under the same lock
mu.Unlock()
Real output:
saw the new menu: 1710500 times
saw a mixed-up menu: 0 times
(The count changes per run: 1710500 and 1883262 in two of ours.)
The second danger, torn values: a value bigger than one machine word (8 bytes on a 64-bit CPU), like this 3-int struct (24 bytes), a string (pointer + length), a slice (pointer + length + capacity) or an interface (type + pointer), may be written and read piece by piece. A racy reader can then see half the old value and half the new one: a menu nobody wrote. For strings, slices, interfaces and maps, a torn (pointer, length) or (type, pointer) pair can make the program read the wrong memory: the memory model says such races "can in turn lead to arbitrary memory corruption". In our run the compiler removed the writes before tearing could happen; with different code or another compiler version, the other failure shows up.
The race detector's cost
// commands: go run . then go run -race .
package main
import (
"fmt"
"os"
"strings"
"sync"
"time"
)
// peak memory of this process, from Linux's /proc
func peakMemory() string {
b, _ := os.ReadFile("/proc/self/status")
for _, line := range strings.Split(string(b), "\n") {
if strings.HasPrefix(line, "VmHWM:") {
return strings.TrimSpace(line[6:])
}
}
return "?"
}
func main() {
start := time.Now()
var mu sync.Mutex
tally := map[int]int{}
var wg sync.WaitGroup
for cook := 0; cook < 100; cook++ {
wg.Go(func() {
for i := 0; i < 10000; i++ {
mu.Lock()
tally[i]++
mu.Unlock()
}
})
}
wg.Wait()
took := time.Since(start).Round(time.Millisecond)
fmt.Println("time:", took, " peak memory:", peakMemory())
}
Real output (two runs):
$ go run .
time: 35ms peak memory: 3048 kB
$ go run -race .
time: 436ms peak memory: 34864 kB
$ go run .
time: 34ms peak memory: 3120 kB
$ go run -race .
time: 493ms peak memory: 34712 kB
About 13x the time and 11x the memory here. /proc/self/status is a Linux file describing the running process; VmHWM ("high water mark") is its peak resident memory. The docs: typically 5-10x memory and 2-20x time. The detector is based on ThreadSanitizer (TSan), a race-detection library from the LLVM project that Go's -race uses. Use -race in tests, CI and test/staging environments; usually not in production.
Running tests with -race in CI
// files: go.mod, shop.go, shop_test.go
// commands: go test . then go test -race .
// ---- shop.go ----
package shop
// Orders counts orders; someone forgot the lock
type Orders struct{ n int }
func (o *Orders) Add() { o.n++ }
func (o *Orders) Count() int { return o.n }
// ---- shop_test.go ----
package shop
import (
"sync"
"testing"
)
func TestTwoCounters(t *testing.T) {
var o Orders
var wg sync.WaitGroup
wg.Go(o.Add) // the app
wg.Go(o.Add) // the phone
wg.Wait()
if o.Count() != 2 {
t.Errorf("Count() = %d, want 2", o.Count())
}
}
Real output (shortened):
$ go test .
ok shop 0.002s
$ go test -race .
==================
WARNING: DATA RACE
Read at 0x00c000012268 by goroutine 10:
shop.(*Orders).Add()
shop.go:6 +0x35
...
Previous write at 0x00c000012268 by goroutine 9:
shop.(*Orders).Add()
shop.go:6 +0x47
...
==================
--- FAIL: TestTwoCounters (0.00s)
testing.go:1617: race detected during execution of test
FAIL
FAIL shop 0.012s
FAIL
o.Add is a method value (episode 20) bound to &o. The plain test passes by luck; with -race the same test fails: "race detected during execution of test".
CI (continuous integration) is a server that builds and tests every change pushed to the repository. Add a step like:
go test -race ./...
./... means "this package and every package below it". Combine with -count=1 (no cached results) and, for flaky timing races, -count=20 to run each test 20 times. A minimal GitHub Actions job:
name: test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.25'
- run: go vet ./...
- run: go test -race -count=1 ./...
Mini project: race hunt
A Stock type with no lock; 50 goroutines take and restock; find the race, fix it.
// ---- stock.go ----
package shop
import "sync"
type Stock struct {
mu sync.Mutex // the fix: added after reading the report
items map[string]int
}
func NewStock() *Stock { return &Stock{items: map[string]int{}} }
func (s *Stock) Restock(item string, n int) {
s.mu.Lock()
defer s.mu.Unlock()
s.items[item] += n
}
// Take removes one item; false if none is left
func (s *Stock) Take(item string) bool {
s.mu.Lock()
defer s.mu.Unlock()
if s.items[item] == 0 {
return false
}
s.items[item]--
return true
}
func (s *Stock) Left(item string) int {
s.mu.Lock()
defer s.mu.Unlock()
return s.items[item]
}
// ---- stock_test.go ----
package shop
import (
"sync"
"testing"
)
func TestStock(t *testing.T) {
s := NewStock()
s.Restock("paneer", 100)
var wg sync.WaitGroup
for i := 0; i < 50; i++ {
wg.Go(func() {
s.Take("paneer")
s.Restock("paneer", 1)
})
}
wg.Wait()
if got := s.Left("paneer"); got != 100 {
t.Errorf("Left = %d, want 100", got)
}
}
Real output with the mutex lines removed (shortened):
$ go test -race .
==================
WARNING: DATA RACE
...
--- FAIL: TestStock (0.00s)
testing.go:1617: race detected during execution of test
FAIL
(Without -race the lock-free version passed in our runs, ok shop 0.002s: exactly the lucky pass that lets a race ship. Under heavier load a map written by many goroutines can also stop with fatal error: concurrent map writes.) With the mutex:
$ go test -race -count=20 .
ok shop 1.017s
Common mistakes (and the real messages)
| Mistake | Real message / result | Why | Fix |
|---|---|---|---|
| "the output is right, so there's no race" | WARNING: DATA RACE · exit status 66 |
races hide behind right answers | go run -race, go test -race |
| testing only the easy path | no report for the racy branch | only code that runs is checked | test every concurrent path, realistic load |
a plain bool flag between goroutines |
Found 2 data race(s) (on done and slip) |
no happens-before; loop may never end | WaitGroup, Mutex, channel, atomic.Bool |
| "one writer, it's benign" | saw the new menu: 0 times |
the compiler removed the racy writes | lock both reads and writes |
| racy strings/slices/interfaces | torn values, possible memory corruption | multiword values are not written at once | synchronise |
| locking only the writer | WARNING: DATA RACE (read without lock) |
the reader isn't ordered | lock on both sides |
CI without -race |
ok shop while the race ships |
passed by luck | go test -race ./... |
-race in production by default |
2-20x time, 5-10x memory | instrumentation cost | tests, CI, staging |
Practice
- Run the race program from episode 45 (
rotis++without a lock) withgo run -race. How many races are reported, and on which line? - Is this a data race? Why?
var x int
var mu sync.Mutex
go func() { mu.Lock(); x = 1; mu.Unlock() }()
time.Sleep(time.Second)
mu.Lock()
fmt.Println(x)
mu.Unlock()
- Replace the
doneflag program's synchronisation with async.Mutexinstead of a WaitGroup, keeping theforloop. Does-racestay quiet? - (Homework) Run
go test -race ./...on one of your projects.
Solution 1
Real result: the program still prints a wrong tally (expected 1000000, tally says 943301 in our run), then Found 2 data race(s) and exit status 66. Both reports point at the rotis++ line: one is a read racing with an earlier write, the other a write racing with an earlier write. The detector reports each distinct pair of clashing source locations and access kinds once, not every lost update.
Solution 2
No. Both accesses hold mu, so one Unlock is synchronized before the other Lock: they are ordered. (The Sleep is not what makes it safe; it only makes it likely that the goroutine runs first, so 1 is printed. Without the sleep it could print 0, which is a race condition in the logic, but still not a data race.)
Solution 3
package main
import (
"fmt"
"sync"
"time"
)
var mu sync.Mutex
var slip string
var done bool
func raju() {
time.Sleep(10 * time.Millisecond)
mu.Lock()
slip = "2 masala dosa"
done = true
mu.Unlock()
}
func main() {
go raju()
for {
mu.Lock()
d := done
mu.Unlock()
if d {
break
}
}
mu.Lock()
fmt.Println("cooking:", slip)
mu.Unlock()
}
Real output with go run -race: cooking: 2 masala dosa, no report. It is correct but still busy-waits, burning a CPU; episode 47's channels fix that.
Quick quiz
1. One goroutine writes x under mu; another prints x without locking. Data race? (From the video.)
A. No: x is protected by mu · B. Yes: the read takes no lock · C. No: only one goroutine writes · D. Only with 2+ CPUs
Answer
B. A mutex orders only accesses that take it, on both sides.
2. What exit status does a program have after the race detector reports a race?
Answer
66 by default (GORACE=exitcode=N changes it).
3. go test -race passes. Is the code race-free?
Answer
Not proven: only the paths and interleavings that ran were checked.
4. Name three synchronising operations.
Answer
Any three of: Unlock → next Lock; wg.Done → wg.Wait returns; channel send → receive; close → receive of "closed"; once.Do; atomic operations; the go statement → goroutine start.
Interview questions
- What is a data race in Go? Two goroutines access the same variable concurrently, at least one writes, and the accesses are not ordered by happens-before.
- How do you find data races? Build/run/test with
-race. It instruments memory accesses (ThreadSanitizer) and reports unordered conflicting accesses, with stacks. - What are the race detector's limits? Only executed code; costs 2-20x time, 5-10x memory; no false positives in practice, but false negatives for paths not run.
- What is the happens-before relation? The transitive closure of sequenced-before (program order in a goroutine) and synchronized-before (between goroutines via sync operations). A write that happens before a read is guaranteed visible.
- Which operations synchronise goroutines in Go? Channel send/receive/close, Mutex/RWMutex Unlock→Lock, WaitGroup Done→Wait, Once, atomics, the
gostatement. - Why is
for !done {}with a plain bool wrong? No synchronisation: main may never seedonechange, and seeing it doesn't imply seeing earlier writes. The memory model says the loop is not guaranteed to finish. - Are any data races benign in Go? No. Racy writes can be optimised away, multiword values can tear, and torn strings/slices/interfaces can corrupt memory.
- What is DRF-SC? Data-race-free programs behave sequentially consistently, as if goroutines took turns on one processor.
- How would you set up CI for concurrent code?
go vet ./...andgo test -race -count=1 ./...on every push; stress with-count=N.
Glossary
| Term | Meaning | Example |
|---|---|---|
| Data race | two goroutines access one variable concurrently, at least one writes, no synchronisation | orders++ in two goroutines |
| Concurrent (accesses) | not ordered: nothing forces one to finish before the other starts | two wg.Go bodies |
| Race detector | Go's tool that reports data races while a program runs | go run -race . |
-race flag |
builds the program with race detection | go test -race ./... |
| ThreadSanitizer (TSan) | the race-detection library (from LLVM) behind -race |
named in the memory model |
| Instrumentation | extra code the compiler adds to record what the program does | every memory access recorded |
| Race report | the detector's output: the two accesses, goroutines, stacks | WARNING: DATA RACE |
| Memory address | where a variable lives in memory | 0x00c000012118 |
| Stack trace | the chain of function calls at a point, with files and lines | main.go:11 +0x2e |
| Exit status 66 | the default exit code after a detected race | GORACE=exitcode=66 |
GORACE |
environment variable with race detector options | GORACE=halt_on_error=1 |
os.Args |
the program's command-line arguments | go run . rush → os.Args[1] == "rush" |
| Visibility | whether and when a write by one goroutine is seen by another | done never seen |
| Go memory model | the official rules for which writes a read may see | go.dev/ref/mem |
| Sequenced before | program order inside one goroutine | write slip, then set done |
| Synchronized before | an ordering between goroutines created by a sync operation | Unlock → next Lock |
| Happens before | chains of sequenced-before and synchronized-before; guarantees visibility | write → Done → Wait → read |
| Synchronising operation | an operation that creates synchronized-before edges | channel send, Unlock, Done |
| DRF-SC | data-race-free programs behave sequentially consistently | no races → as if on one CPU |
| Sequential consistency | every goroutine's operations appear in one global order, each in program order | taking turns on one CPU |
| Busy waiting | spinning in a loop to notice a change | for !done {} |
| Benign race | a race believed harmless; in Go there is no such thing | "only one writer" |
| Compiler optimisation | the compiler changing code to run faster without changing single-goroutine results | racy writes removed |
| Assembly | human-readable machine instructions | JMP 0 |
-gcflags=-S |
asks the Go compiler to print the assembly it makes | go build -gcflags=-S board.go |
| Machine word | the CPU's natural unit, 8 bytes on 64-bit | an int |
| Multiword value | a value larger than one machine word | string, slice, interface, 3-int struct |
| Torn value | a value read half before and half after a write | a menu nobody wrote |
| Memory corruption | a program reading or writing memory it shouldn't | a torn (pointer, length) pair |
/proc/self/status |
Linux file describing the current process | VmHWM: 3048 kB |
| Peak memory (VmHWM) | the most memory a process held at once | 3 MB vs 35 MB |
| CI (continuous integration) | a server that builds and tests every pushed change | GitHub Actions |
./... |
this package and all packages below it | go test -race ./... |
-count=N |
run each test N times (and -count=1 disables the test cache) |
-count=20 |
Summary
- A data race: two goroutines, one variable, at least one write, no synchronisation. It can hide behind a right answer.
-raceongo run,go test,go build,go installfinds races at runtime; reports show the two accesses (same address), goroutines and lines; exit status 66.- It sees only code that runs: test every concurrent path, under realistic load.
- The memory model: a write is guaranteed visible only if it happens before the read, via synchronising operations (Unlock→Lock, Done→Wait, channels, Once, atomics,
go). A plain bool flag is not one. - No race is benign: racy writes can be removed by the compiler (our board:
saw the new menu: 0 times), multiword values can tear and corrupt memory. -racecosts about 2-20x time and 5-10x memory: rungo test -race ./...in CI.- "Don't be clever": use mutexes, WaitGroups and channels.
Next episode: Channels, the basics: make(chan T), send and receive, unbuffered and buffered channels, len and cap, close, range, the comma-ok receive, directional channels, channels as first-class values.