CodeGym /행동 /Go SELF /go test -race — what it catches and what it does not catc...

go test -race — what it catches and what it does not catch

Go SELF
레벨 71, 레슨 0
사용 가능

1. Why go test -race is needed

If a regular bug is like a hole in a pipe, where water flows all the time, steadily, and predictably, then a data race is like a cat that sometimes walks through a wall. You cannot properly “complain” about it: “well, there it was a minute ago!” That is exactly why Go has a special tool — the race detector, which helps make the invisible visible.

When we have concurrent code, or code that may become concurrent, such as HTTP handlers, a worker pool, or parallel tests, we want to answer a simple question: “is there any simultaneous write/read of the same memory without synchronization?” That is the main purpose of go test -race.

It is important not to confuse the terms. There is a broader concept called race condition: when the result depends on the order of events. It can happen even without simultaneous access to memory. A classic example is “whoever gets there first wins” in concurrent logic, as in the situation “take the first response and ignore the rest.” A data race is specifically about memory: when multiple goroutines access the same place in memory without an agreement.

The Go -race flag helps catch exactly data races. And that alone can save you days of life, a couple of nerve cells, and one gray hair, or twenty.

2. What a data race is

To feel what exactly “counts as a race,” it is useful to state the formal rule in simple words. This will be “legal language” for a moment, but I will translate it into human language.

A data race occurs when:

  1. there are two or more goroutines,
  2. they access the same memory region (a variable, a struct field, a map element, a slice element, and so on),
  3. at least one access is a write,
  4. and there is no synchronization between these accesses, meaning there is no “agreement” that makes the order safe (mutexes, channels, atomics, and other recognized ways).

Two subtleties that often surprise beginners.

The first subtlety is that “the same memory region” is not only “global variable n.” It can be a field inside a struct stored on the heap, a shared map, a shared slice, a shared buffer, a shared bytes.Buffer, and so on. In other words, a “shared object” matters more than a “global variable.”

The second subtlety is that a race can happen even when the result seems “correct.” For example, you expect two increments to give 2, and sometimes you really do get 2. But the very fact that the write was unsynchronized is already a defect. -race catches the access-model defect, not just the “wrong value.”

3. How to run go test -race

When you run tests with the -race flag, Go builds and runs the test binary in a special mode: instrumentation is added so that during execution it tries to notice unsynchronized memory accesses.

This usually looks like this, as a reference, not as a “mandatory command”:

go test -race ./...

You can also run it for a single package:

go test -race ./internal/task

Or a single test, which is handy when you already found a suspicious place:

go test -race -run TestInMemoryStore_Add_Race ./internal/task

There is an important practical consequence: -race makes the program noticeably slower and more memory-hungry. That is normal. It is not needed “all the time in production”; it is needed as a diagnostic spotlight: turn it on, look, turn it off. Like a flashlight in a basement you do not want to move into.

And one more point for understanding the big picture. The race detector is not something new and has been part of the Go ecosystem for many years; for example, in the Go 1.3 notes, a faster race detector was mentioned among the improvements. This matters psychologically: the tool is mature and practical, not an “experimental toy.”

4. An example of a race in an in-memory task store

Let us imagine that we are developing an educational app, a task manager: task storage, task creation, task listing. Suppose we started with a simple in-memory store based on map[int]Task and automatic numbering with nextID. While everything is single-threaded, it is beautiful. But as soon as parallel scenarios appear, for example several workers import tasks, or tests run concurrent operations, the “simple” becomes dangerous.

Here is a very simplified version of a store without protection:

package task

type InMemoryStore struct {
	nextID int
	items  map[int]string
}

func NewInMemoryStore() *InMemoryStore {
	return &InMemoryStore{nextID: 1, items: make(map[int]string)}
}

func (s *InMemoryStore) Add(title string) int {
	id := s.nextID
	s.nextID++
	s.items[id] = title
	return id
}

From the business-logic point of view, everything sounds fair: take nextID, increment it, put the task into the map. But according to the memory model, there are already two shared points here: nextID and items.

Now a test that performs two concurrent writes. It is tiny, almost funny — but that is exactly the good teaching moment: races often begin with “what could possibly happen here?”

package task

import (
	"sync"
	"testing"
)

func TestInMemoryStore_Add_Race(t *testing.T) {
	s := NewInMemoryStore()

	var wg sync.WaitGroup
	wg.Add(2)

	go func() { defer wg.Done(); _ = s.Add("a") }()
	go func() { defer wg.Done(); _ = s.Add("b") }()

	wg.Wait()
}

If you run this test without -race, it will most likely be green. And this is where the brain makes a dangerous conclusion: “so everything is fine.” The point of -race is to tell the brain: “no, it is not fine, you were just lucky.”

5. How to read a race detector report

A race detector report usually scares beginners with its size: some goroutines, some stacks, some memory addresses. The good news is that you do not need to understand everything. You need to understand two things: where one side of the conflict was, and where the other was.

A typical report, intentionally shown in a simplified form rather than the full output:

WARNING: DATA RACE
Write at ... by goroutine 7:
  ... file.go:NN

Previous read at ... by goroutine 8:
  ... file.go:MM

The meaning is this.

The first part shows one access, for example a write, and the call stack takes you to the line where the write actually happened. The second part shows another conflicting access, for example a read or another write, and also gives you the stack and the line.

Here is a simple way to look at it as a diagram:

goroutine A: writes to X  ----\
                               => conflict on X (no synchronization)
goroutine B: reads X      ----/

What to look for first.

Look at your files and your lines. Memory addresses and internal runtime calls are almost never your starting point. Usually it is enough to find two lines in your code and ask: “why can these two pieces of code run at the same time and touch the same thing?”

And one more important practical point: a race report does not always mean that “both places are equally guilty.” Often one access is a normal “work with state” operation, while the other is “someone accidentally went there in parallel.” The fix usually consists of introducing a protocol: either protect the critical section with a mutex, or restructure the interaction through channels, or remove shared state altogether.

6. What -race catches and what it does not catch

With -race, it is easy to start believing in magic: “turn it on, run it, and everything is correct.” That is a very dangerous belief. The race detector is powerful, but it has limits: it catches what actually happened during the run, and it catches only data races.

It is useful to keep this table in mind:

Situation Will -race catch it? Why
Two goroutines read and write the same variable without a mutex/channel Yes This is a classic data race: shared memory + write without synchronization
Concurrent access to a map without protection Yes (and often it will also crash without -race) map is not thread-safe, and the tool can see unsynchronized accesses well
A logic error of “whoever gets there first is right,” but without shared memory No This is a race condition as a logical dependence on order, but not a data race
A deadlock (everyone waits for everyone else) No This is not a data race, but a problem with the locking/channel protocol
A race that theoretically exists, but did not happen in this run May not catch it The tool is dynamic: if there was no conflicting interleaving, there was no signal
A bug caused by the wrong order of actions inside a single goroutine No This is just a regular error, with no concurrency

Notice the third row: a race condition is broader than a data race. We already encountered this when talking about concurrent patterns and timeouts: sometimes correctness depends on the order of events. But -race is not a detector of “bad scenarios”; it is a detector of “bad memory accesses.”

Another boundary worth remembering: the absence of a -race report is not proof that there are no races. It is proof that there were no races in this particular run on this machine, with this goroutine schedule. In other words, it is a very strong signal that “this is definitely bad here,” but not an absolute guarantee that “everything is definitely good everywhere.”

7. How to increase the chance of catching a race

The problem with races is that they sometimes hide. You turn on -race, run the test — silence. And then there is a temptation to say: “well, done, let us move on.” But it is better to say: “let us give the race a chance to show itself.”

The simplest amplifier is to repeat the concurrent operation many times. In tests, this is done trivially with a loop. For example, we can do not 2 concurrent Add calls, but 1000, distributed across several goroutines. The balance matters here: the test should remain fast, but “noisy enough” so that a conflict is likely.

Here is an example of an “amplified” test, note that it is still short and does not use time.Sleep:

package task

import (
	"strconv"
	"sync"
	"testing"
)

func TestInMemoryStore_Add_RaceMany(t *testing.T) {
	s := NewInMemoryStore()

	var wg sync.WaitGroup
	for g := 0; g < 4; g++ {
		wg.Add(1)
		go func(g int) {
			defer wg.Done()
			for i := 0; i < 200; i++ {
				_ = s.Add("t" + strconv.Itoa(g*1000+i))
			}
		}(g)
	}
	wg.Wait()
}

Why do we avoid time.Sleep as an “amplifier”? Because Sleep makes tests flaky: on one machine they “made it,” on another they “did not.” Our goal is for the test to be repeatable in meaning: we run concurrent load and check that there are no races under that load. If you add Sleep, you start testing timings, not your code.

If you need to run the tests multiple times, the -count=1 flag is often used to disable test result caching and actually execute them every time. This is not magic and not a “race fix”; it is simply a way to be sure you are really running the test and not reading an old result.

8. How to fix a race: mutex and rechecking

Now for the pleasant part: the fix. In our InMemoryStore, we have shared nextID and a shared map. The state-changing logic should become a critical section.

Let us add sync.Mutex and protect the “take id → increment → write to map” section:

package task

import "sync"

type InMemoryStore struct {
	mu     sync.Mutex
	nextID int
	items  map[int]string
}

func (s *InMemoryStore) Add(title string) int {
	s.mu.Lock()
	defer s.mu.Unlock()

	id := s.nextID
	s.nextID++
	s.items[id] = title
	return id
}

This change seems small, but in meaning it is huge: we are introducing an agreement. Now even if Add is called from 10 goroutines at the same time, access to nextID and items becomes sequential.

Then you run the same tests with -race, and the tool stops complaining. That is exactly the cycle you should build into a habit: “write concurrent code → make a test with concurrent load → run it with -race.”

And here is an important remark: a mutex is not the only solution. Sometimes it is better to design the architecture without shared state, for example by passing operations through a channel to a single state-owning goroutine. But at our current level, a mutex is a direct and honest tool: easy to read, predictable to use.

9. Typical mistakes when working with go test -race

Mistake #1: thinking that -race proves the absence of races.
It is tempting to live in a world where one command gives a mathematical guarantee. But -race is a dynamic tool: it shows what happened during execution. If a race depends on a rare goroutine schedule, it may not appear in one run. So silence from -race is a good sign, but not a safety certificate.

Mistake #2: treating races with time.Sleep.
When you see that “sometimes” two threads interfere with each other, the hand reaches for a pause: “let one of them finish first.” This almost always makes things worse. You are not introducing a protocol; you are introducing guesswork based on timing. On another CPU, under another load, with another scheduler, everything will fall apart again.

Mistake #3: protecting only writes while leaving reads unprotected.
Beginners often put a mutex “at the write site” and think that is enough. But if another goroutine reads the same field without a mutex, that is still a data race. The protocol must be symmetric: either you agree that access to the field is always under a lock, or you agree that the field is immutable after initialization, or you use another safe mechanism.

Mistake #4: making parallel tests that share common state.
Even if production code is perfect, the tests themselves can create a race: a shared global store, a shared map with fixtures, a shared counter, a shared temporary file without isolation. After that, -race complains, and you fix the wrong place. The discipline is simple: each test creates its own state, especially if there is t.Parallel().

Mistake #5: ignoring the race report and “fixing” things at random.
The report almost always gives two points: where one access is, and where the second is. If you start randomly wrapping everything in mutexes, you risk ending up with either complex code, or deadlocks, or simply losing understanding of what you are protecting. It is better to follow the report: find the two lines, understand the shared object, choose one clear protocol.

1
과제
Go SELF, 레벨 71, 레슨 0
잠금
고장난 점수판
고장난 점수판
1
과제
Go SELF, 레벨 71, 레슨 0
잠금
출입증 발급
출입증 발급
1
과제
Go SELF, 레벨 71, 레슨 0
잠금
맵 스냅샷
맵 스냅샷
1
과제
Go SELF, 레벨 71, 레슨 0
잠금
데이터 레이스 없는 제곱 계산
데이터 레이스 없는 제곱 계산
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION