Golang / GoLang Concurrency Mastery Interview Questions
What are the specific happens-before guarantees for channel operations in Go's memory model?
Go's memory model specifies precise happens-before rules for channels. Knowing these is necessary for writing correct concurrent code that works across CPU architectures without data races.
| Operation | Guarantee |
|---|---|
| Send on a channel | Completes before the receive from that send returns |
| Close of a channel | Happens-before a receive that returns the zero value (closed-channel read) |
| Receive from unbuffered channel | Happens-before the send on that channel completes |
| kth receive from buffered (cap=C) | Happens-before the (k+C)th send completes — enables semaphore semantics |
// Rule 1: send completes before receive returns
var data string
ch := make(chan struct{})
go func() {
data = "shared" // write
ch <- struct{}{} // send: completes before <-ch returns
}()
<-ch // receive: data write is guaranteed visible
fmt.Println(data) // "shared" — safe
// Rule 2: close happens-before zero-value receive
var ready bool
done := make(chan struct{})
go func() { ready = true; close(done) }()
<-done
fmt.Println(ready) // guaranteed: true
// Rule 3: unbuffered — receive happens-before send completes
// (sender cannot proceed until receiver has the value)
// Rule 4: buffered channel as semaphore
// cap=1 channel: 1st receive happens-before 2nd send completes
limit := make(chan struct{}, 1)
var shared int
go func() {
limit <- struct{}{} // 1st send
shared = 42
<-limit // 1st receive: happens-before 2nd send
}()
go func() {
limit <- struct{}{} // 2nd send — cannot complete until 1st recv done
fmt.Println(shared) // guaranteed to see 42
<-limit
}()
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...
