Lab 01: Memory Model & Escape Analysis
Overview
Prerequisites
Step 1: Go Memory Model — Happens-Before
// happens_before.go
package main
import (
"fmt"
"sync"
)
var (
msg string
done bool
mu sync.Mutex
)
// WRONG: no synchronization — data race
func unsafeCommunicate() {
go func() { msg = "hello" }()
// msg might not be visible here!
for !done {
}
fmt.Println(msg)
}
// CORRECT: channel establishes happens-before
func safeCommunicate() {
ch := make(chan struct{})
go func() {
msg = "hello from goroutine"
close(ch) // write happens-before close
}()
<-ch // close happens-before receive
fmt.Println(msg) // safe to read
}
func main() {
safeCommunicate()
// Mutex also establishes happens-before
mu.Lock()
msg = "protected write"
mu.Unlock()
mu.Lock()
fmt.Println(msg) // guaranteed to see "protected write"
mu.Unlock()
}Step 2: Stack vs Heap Allocation
Step 3: Escape Analysis with -gcflags="-m"
-gcflags="-m"Step 4: sync/atomic — Basic Operations
sync/atomic — Basic OperationsStep 5: atomic.Pointer[T] — Type-Safe Pointer Swapping
atomic.Pointer[T] — Type-Safe Pointer SwappingStep 6: Memory Ordering — Relaxed vs Sequential
Step 7: Race Detector
Step 8: Capstone — Lock-Free Stack
Summary
Concept
Key Tool
When to Use
Last updated
