Why This Happens
Go's race detector (go run -race) finds concurrent unsynchronized access to shared variables. A data race occurs when two goroutines access the same variable and at least one is writing. This leads to unpredictable behavior and bugs that are hard to reproduce.
The Problem
var counter int
func main() {
for i := 0; i < 1000; i++ {
go func() {
counter++ // data race
}()
}
time.Sleep(time.Second)
fmt.Println(counter)
}The Fix
var (
counter int
mu sync.Mutex
)
func main() {
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
counter++
mu.Unlock()
}()
}
wg.Wait()
fmt.Println(counter)
}Step-by-Step Fix
- 1
Identify the race
Run your program with go run -race or go test -race to get a detailed report of the conflicting accesses.
- 2
Understand the shared state
Determine which variable is shared and which goroutines are reading and writing to it.
- 3
Add synchronization
Protect the shared variable with sync.Mutex, sync.RWMutex, sync/atomic operations, or redesign to use channels.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free