Golang / GoLang Basics Interview Questions
What is a data race in Go and how do you detect one?
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, non-deterministic behaviour — results vary between runs and can silently corrupt data.
// DATA RACE â unsafe counter 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++ // READ + INCREMENT + WRITE â not atomic! }() } wg.Wait() fmt.Println(counter) // less than 1000 â data was lost! // DETECT: go run -race main.go or go test -race ./... // Race detector output: // ================== // WARNING: DATA RACE // Write at 0x... by goroutine 8: main.main.func1() :12 // Previous write at 0x... by goroutine 7: main.main.func1() :12 // ================== // FIX 1: sync.Mutex var mu sync.Mutex go func() { mu.Lock(); counter++; mu.Unlock() }() // FIX 2: atomic operation (faster for simple numeric ops) var atomicCounter int64 go func() { atomic.AddInt64(&atomicCounter, 1) }() // FIX 3: channel â one goroutine owns the counter inc := make(chan struct{}, 100) go func() { n := 0; for range inc { n++ } }() inc <- struct{}{} // safe
More Related questions...