Member-only story

Data races in go: What they are and how to avoid them like a Pro

Kirubakaran
Dev Genius
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:

  1. Two or more goroutines access the same memory location
  2. At least one access is a write
  3. 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:

  1. Both the main goroutine and the anonymous goroutine access n.
  2. At least one of them modifies n.
  3. There is no synchronization to ensure orderly execution.

The result is undefined behavior, as the order of operations is unpredictable.

--

--

Published in Dev Genius

Coding, Tutorials, News, UX, UI and much more related to development

Written by Kirubakaran

Software Engineer expertise on C, C++, Golang, Python, Docker, Kubernetes.

No responses yet

What are your thoughts?