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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
