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 }()
More Related questions...