Golang / Golang Internals and Memory Management Interview Questions
What is the Go race detector and how does it work?
The race detector (-race flag) instruments the binary to track every memory access and detect data races — concurrent reads and writes to the same memory without synchronisation. It uses the ThreadSanitizer (TSan) C library under the hood.
// Run with race detection
// go run -race main.go
// go test -race ./...
// go build -race -o myapp
// Example of a data race
var counter int
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // DATA RACE: concurrent unsynchronised write
}()
}
wg.Wait()
// Race detector output:
// ==================
// WARNING: DATA RACE
// Write at 0x00c000016090 by goroutine 7:
// main.main.func1()
// /tmp/main.go:14 +0x38
// Previous write at 0x00c000016090 by goroutine 6:
// main.main.func1()
// /tmp/main.go:14 +0x38
// ==================
// Fix: use atomic or mutex
var atomicCounter int64
atomic.AddInt64(&atomicCounter, 1) // race-free
// Race detector overhead:
// CPU: 5–20x slower
// Memory: 5–10x more
// Not suitable for production (unless you accept the overhead)
// Ideal in CI and -race enabled test suitesThe race detector uses happens-before analysis (Vector Clocks) to determine whether two conflicting accesses could overlap in time. It reports every detected race with full stack traces for both the current access and the previous conflicting access, making it extremely useful for tracking down subtle bugs. It is recommended to always run go test -race ./... in CI pipelines.
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...
