Member-only story
Data races in go: What they are and how to avoid them like a Pro
Published in
3 min readFeb 5, 2025
You can read this same article free here
Concurrency is one of the most salient features in golang and in majority of the cases golang is apt for that purpose. But it has its own challenges. Needless to say, data races are notoriously famous for this. In this blog post, Let’s see what they are and how to debug in a program etc.
What Is a Data Race?
A data race occurs when:
- Two or more goroutines access the same memory location
- At least one access is a write
- There’s no synchronization between accesses
Example
func main() {
n := 0
go func() { n++ }() // Goroutine1: increments n
n++ // Main goroutine: incrments n
fmt.Println(n)
}
In this code:
- Both the main goroutine and the anonymous goroutine access n.
- At least one of them modifies n.
- There is no synchronization to ensure orderly execution.
The result is undefined behavior, as the order of operations is unpredictable.