Golang / GoLang Concurrency Mastery Interview Questions
What is a data race in Go, how do you detect it, and what are the three main fixes?
A data race occurs when two or more goroutines access the same memory location concurrently, at least one access is a write, and there is no synchronisation between them. Data races produce undefined behaviour: silent data corruption, non-deterministic results, or rare crashes.
// Classic data race â unsynchronised increment from multiple goroutines var counter int var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func() { defer wg.Done() counter++ // DATA RACE: read-increment-write is not atomic }() } wg.Wait() fmt.Println(counter) // may print anything less than 1000 // DETECT: go run -race main.go OR go test -race ./... // Race detector output: // ================== // WARNING: DATA RACE // Write at 0x... by goroutine 7: main.main.func1() :11 // Previous write at 0x... by goroutine 6: main.main.func1() :11 // ================== // FIX 1: sync.Mutex var mu sync.Mutex var safe int go func() { mu.Lock(); safe++; mu.Unlock() }() // FIX 2: atomic (faster for simple numeric ops) var atomic64 int64 go func() { atomic.AddInt64(&atomic64, 1) }() // FIX 3: channel â single goroutine owns the variable type incMsg struct{} ch := make(chan incMsg) go func() { n := 0 for range ch { n++ } }()
The race detector adds 5–10× CPU overhead and uses ThreadSanitizer (TSan) under the hood. It reports every detected race with full stack traces for both the current and prior conflicting access — making the root cause straightforward to identify. Always run your test suite with -race.
More Related questions...