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.
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...
