1. Why it is important to talk about data race
When you launch several goroutines for the first time, your brain automatically expects the program to behave “almost as usual”, only faster. And sometimes it really does look normal. But concurrent code often does not break immediately: it can “work” for years and then crash during a client demo, right at the moment when you confidently say, “well, it is all simple here.” Data race is like a crack in a foundation: a house may stand until rain starts, frost arrives, or just a “bad scheduler day” happens.
The key idea for today: data race is not a “rare bug”, but a violation of the rules of the game. If a race exists, the program becomes unpredictable, and “it sometimes works” only means “you have been lucky so far.”
Why “it sometimes works” is especially dangerous
In a sequential program, “first line 1, then line 2” is a fairly honest agreement with reality. In a concurrent program, the Go scheduler can break goroutine execution into small pieces and switch between them whenever it wants: because of load, timers, system calls, number of cores, or simply because that is how things happened to line up.
As a result, an unpleasant effect appears: you run the program 10 times and get 10 different behavioral variants. And here the beginner’s brain often draws the wrong conclusion: “Well, that just means the order of console output is fluctuating.” Sometimes yes. But sometimes the meaning of the computation is fluctuating.
Let us look at a simple flowchart of interleaved actions:
flowchart TD
A[goroutine #1 reads counter] --> B[goroutine #1 increments locally]
C[goroutine #2 reads counter] --> D[goroutine #2 increments locally]
B --> E[goroutine #1 writes counter]
D --> F[goroutine #2 writes counter]
If two read/write flows overlap, one result may overwrite the other. And the most unpleasant part: sometimes this happens, sometimes it does not — because it depends on the random execution schedule.
2. Data race in simple words
A data race occurs when two or more goroutines access the same memory area at the same time, and at least one access is a write, while there is no coordination (synchronization). That is all. This is a short definition at the “reality check” level.
To make it easier to keep in mind, it is useful to imagine this table:
| Situation | Do several goroutines touch the same variable? | Is there a write? | Is there coordination? | Is this a data race? |
|---|---|---|---|---|
| Only reading a shared value | yes | no | does not matter | no |
| Read + write without rules | yes | yes | no | yes |
| Write + write without rules | yes | yes | no | yes |
| Read/write, but strictly by agreement (synchronization) | yes | yes | yes | no |
We are not introducing synchronization today as a new tool (no Mutex, atomic, or channels). We are learning to recognize the problem and write code so that we do not create a shared write point “all in one heap”.
3. Classic races: from counter++ to map
Why counter++ is not “one operation”
Let us start with an example that looks so innocent that you want to give it a like and ship it to production.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
counter := 0
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // data race
}()
}
wg.Wait()
fmt.Println("counter =", counter) // may be 1, 2, or 3
}
Why is this a race? Because counter++ is logically three steps: read counter, add 1, write back. And these steps can get interleaved between goroutines.
Imagine that counter was 0. Two goroutines almost simultaneously read 0. Both increment to 1. Both write 1. As a result, instead of the expected 2, you get 1. And yes, sometimes you will get 2 if you are “lucky” and the executions do not overlap.
WaitGroup does not make data safe
After the previous lecture, it is easy to catch yourself thinking: “Okay, I put wg.Wait(), so everything is under control.” Alas, WaitGroup is a barrier at the exit, not road markings.
It guarantees only one thing: all goroutines have finished. But it does not guarantee that they did not fight over the same variable while working.
To feel the difference, you can mentally rephrase it: WaitGroup answers the question “when can we continue?”, but not the question “what happens if they write to the same place at the same time?”
From a practical point of view, this means: “I waited for completion” is not the same as “I got a correct result.”
Races in “real” code: structs, fields, and a shared slice
While we were racing an int, everything looked like a toy. But in a real application you almost always share not one int, but a struct or a slice, and the race becomes less obvious.
Imagine that we have a piece of our training application, a hypothetical task manager, and we want to process tasks in parallel and update statistics.
package main
import (
"fmt"
"sync"
)
type Stats struct {
Done int
}
func main() {
var wg sync.WaitGroup
stats := Stats{}
for i := 0; i < 3; i++ {
wg.Add(1)
go func() {
defer wg.Done()
stats.Done++ // data race: shared object, shared write
}()
}
wg.Wait()
fmt.Println("done =", stats.Done) // may be 1, 2, or 3
}
Here the race is already “hidden” behind a struct field. But in essence, it is the same counter++, just dressed up more neatly.
A similar trap is a shared slice and append. We already discussed that a slice is “header + underlying array”, and append can change length, capacity, and even reallocate the array. If several goroutines do append to the same slice without a protocol, you get a lottery: from “elements disappeared” to “data broke”. So, yes, append into a shared slice from different goroutines is almost always a red zone.
A separate danger star: concurrent writes to map
With map in Go there is a peculiarity: concurrent writes (and often write+read) without coordination do not just give “the wrong result”, they can cause the process to abort.
Let us look at an example:
package main
import (
"sync"
)
func main() {
var wg sync.WaitGroup
m := make(map[int]int)
for i := 0; i < 5; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
m[i] = i // unsafe: concurrent write to map
}(i)
}
wg.Wait()
}
Sometimes you will see a panic like fatal error: concurrent map writes. Sometimes it will “pass”, and you will not notice anything at all (which, as we already agreed, is not a reason to celebrate). The bad news is that “it did not crash” does not mean “it is correct”.
4. How to avoid races without new primitives
At this stage of the course, we still do not have tools for synchronizing access to shared memory (we are deliberately not using them today), but that does not mean we are helpless. The most workable beginner recipe sounds like this: each goroutine writes only to its own memory area, and one goroutine combines the results after wg.Wait().
This idea is very much in line with the Go approach of “do not communicate by sharing memory” — it is often phrased as “share memory by communicating”, meaning that instead of shared writes, it is better to build communication and clear ownership boundaries.
We are not using channels yet (that will come later), so let us do “communication through preallocated cells”.
Mini case: count task contributions in parallel
Suppose we have tasks, and we want to count how many “done tasks” are in the set. Parallelizing for the sake of parallelizing is pointless, but as a learning example it is perfect.
First, the bad version (race):
package main
import (
"fmt"
"sync"
)
type Task struct {
Title string
Done bool
}
func main() {
tasks := []Task{
{"Read Go book", true},
{"Write code", true},
{"Touch grass", false},
}
var wg sync.WaitGroup
doneCount := 0
for _, t := range tasks {
wg.Add(1)
go func(t Task) {
defer wg.Done()
if t.Done {
doneCount++ // data race
}
}(t)
}
wg.Wait()
fmt.Println("doneCount =", doneCount) // may be 1 or 2
}
Now let us make a version without a race, because each goroutine writes to its own cell marks[i], and we do the summation after waiting:
package main
import (
"fmt"
"sync"
)
type Task struct {
Title string
Done bool
}
func main() {
tasks := []Task{
{"Read Go book", true},
{"Write code", true},
{"Touch grass", false},
}
var wg sync.WaitGroup
marks := make([]int, len(tasks))
for i := 0; i < len(tasks); i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
if tasks[i].Done {
marks[i] = 1
}
}(i)
}
wg.Wait()
sum := 0
for i := 0; i < len(marks); i++ {
sum += marks[i]
}
fmt.Println("doneCount =", sum) // doneCount = 2
}
The key magic here is not in WaitGroup, but in the fact that there is no shared variable that everyone writes to. Each goroutine fills its own cell, so it does not compete for the same place in memory. And reading marks starts only after wg.Wait(), when all writes are finished.
5. How to think about correctness: ownership and the reading moment
A “race” can happen even without ++
Beginners often think: “A race is when I do counter++.” That is a common association, but a race is broader than that. It is enough for one thread to write while another reads “at the same time”, and you are already in the zone of undefined behavior.
For example, one thread updates a struct field, and another prints the whole struct. Or one thread changes an element in a slice, and another builds a report string from that slice. Even if the program “seems” not to crash, you may get partially updated data.
In everyday terms, it looks like “one person is rewriting a shopping list while another is photographing the sheet at that moment.” The photo will be taken, but the question is: what exactly will be on it? “Bread” has already been added, “milk” is still being erased, and “cheese” suddenly looks like “chese” because the pen was mid-stroke.
Two questions that save you from chaos
A very useful habit is to say out loud (or in a comment) two questions.
First question: which goroutine is considered the “owner” of this value and has the right to change it? If the answer is “well, everyone a bit”, you are almost certainly on the road to a race.
Second question: when are other goroutines allowed to read this value? If the answer is “well, any time, it is just a number”, that is also a warning sign. In concurrent code, “any time” needs to be replaced with “after we have waited for completion” or “after the data has been published by agreement”.
At the level of today’s tools (goroutine + WaitGroup), the simplest agreement sounds like this: write in parallel, read only after wg.Wait(). This is not a universal law of the universe, but it is a good starter pattern that already saves you from many problems.
6. Typical mistakes
Mistake #1: “I added a WaitGroup, so there is no race.”
WaitGroup waits for completion; it does not protect data. It guarantees that the work has finished, but it does not guarantee that the work was done without simultaneous writes to the same memory. If inside a goroutine you do x++ on a shared variable, the race remains — you just now reliably wait for its consequences.
Mistake #2: “If the program does not crash, everything is fine.”
With races, this is especially tricky: they often show up only under load, on different hardware, in another runtime version, or “when the stars align”. The absence of a crash does not prove correctness. In this sense, “it sometimes works” is exactly a bad sign: you do not control the behavior.
Mistake #3: “I am writing to a slice, not to one variable — so it is safe.”
A slice is not “many independent variables”, but a structure with a shared underlying array. If two goroutines write to the same slice without strict index separation or without a protocol, you can easily get overlaps, especially with append. Even if the indexes are different, the problem can appear if one goroutine changes the length/capacity and another assumes the slice structure is stable.
Mistake #4: “With map it is like a dictionary: insert and forget.”
A regular map in Go is not designed for concurrent writes without coordination. In the best case you get incorrect data; in the worst case the process aborts. And once again: wg.Wait() does not help here, because the race happens before waiting.
Mistake #5: “So what, I am only reading a shared object.”
Reading a shared object is safe only when you are sure nobody is writing to it at the same time. If at least one goroutine writes, reading becomes part of the race. A typical scenario: one goroutine updates statistics, another prints a report “in real time”. Without a protocol, this turns into a generator of phantom bugs.
GO TO FULL VERSION