Golang / GoLang Concurrency Mastery Interview Questions
What is Go's memory model and why does it matter for concurrent code?
Go's memory model defines which memory operations in one goroutine are guaranteed to be visible to operations in another. Without understanding it, concurrent code may appear to work correctly in tests but fail silently in production under different compiler optimisations or CPU architectures.
| Operation | Guarantee |
|---|---|
| go f() | All operations before the go statement happen-before f() starts executing |
| Goroutine exit | NOT automatically visible — use WaitGroup, channel, or other sync |
| ch <- v (send) | The send completes before the corresponding receive returns |
| close(ch) | The close happens-before any receive that returns the zero value |
| mu.Unlock() | The nth Unlock() happens-before the (n+1)th Lock() on the same mutex |
| once.Do(f) | The single execution of f happens-before any once.Do() returns |
// WRONG: no happens-before between goroutine exit and main reading data
var data string
go func() { data = "hello" }()
// time.Sleep(time.Second) // WRONG: Sleep is not a sync primitive
fmt.Println(data) // may see empty string — data race!
// CORRECT: channel close establishes happens-before
done := make(chan struct{})
go func() {
data = "hello" // write
close(done) // happens-before any <-done returns
}()
<-done // happens-after close(done) → sees data = "hello"
fmt.Println(data) // guaranteed: "hello"
// WHY Sleep fails:
// The CPU or compiler may keep data in a register.
// Sleep does not cause any memory barrier.
// Only explicit synchronisation primitives create happens-before edges.
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...
