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