Explain write barriers and mark assists
Explain write barriers and mark assists
Application goroutines (mutators) can change pointers while GC scans. In Go 1.23 the compiler inserts write barriers for relevant pointer stores; during marking the hybrid barrier preserves tracing information about overwritten and newly stored references. The runtime can require allocating goroutines to perform mark work (mark assists) so allocation does not outrun marking indefinitely. A GC write barrier is not a mutex, atomic operation or a replacement for synchronization.
package main
import ( "fmt" "runtime")
type Node struct{ Value int }
var root *Node
//go:noinlinefunc publish(n *Node) { root = n }func main() { publish(&Node{9}) runtime.GC() fmt.Println(root.Value)}The global pointer store is a useful compiler inspection target. On Go 1.23 amd64, build with go build -gcflags=-S main.go and inspect publish for the conditional runtime write-barrier path. The exact assembly is version- and architecture-dependent. The printed value checks correctness, not whether a barrier ran on that execution.
Expected output:
9Observe the assist CPU counter
package main
import ( "fmt" "runtime" "runtime/metrics")
var sink []byte
func read() float64 { s := []metrics.Sample{{Name: "/cpu/classes/gc/mark/assist:cpu-seconds"}} metrics.Read(s) return s[0].Value.Float64()}func main() { a := read() for i := 0; i < 256; i++ { sink = make([]byte, 16<<10) } runtime.GC() b := read() fmt.Println(b >= a) runtime.KeepAlive(sink)}The metric counts estimated cumulative CPU seconds spent assisting marking. A zero delta is valid: the runtime may finish the workload with background workers or use previously earned credit. An increase is not wall-clock latency. Compare repeated representative workloads and allocation rates; never require a positive increase in a tiny unit test.
Expected output:
trueTry it locally
Publish an immutable pointer through atomic.Pointer, load it in a goroutine and send the value through a channel. Join via the receive.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Garbage collection 02: Explain write barriers and mark assists
Check the lesson objective before moving on.
What does a GC write barrier protect?
What is a mark assist?