Analyze contention and false sharing
Analyze contention and false sharing
Contention occurs when concurrent work competes for a shared resource such as a mutex. False sharing occurs when independent writes touch memory in the same hardware cache line, causing coherence traffic even without a data race. Start with correctness and representative parallel workloads; then use mutex/block profiles and controlled layout experiments.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "sync" "testing")
type counter struct { mu sync.Mutex n int}
func (c *counter) add(n int) { c.mu.Lock(); c.n += n; c.mu.Unlock() }func TestLesson(t *testing.T) { var c counter var wg sync.WaitGroup for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done() for j := 0; j < 100; j++ { c.add(1) } }() } wg.Wait() if c.n != 400 { t.Fatal(c.n) }}func BenchmarkShared(b *testing.B) { var c counter b.RunParallel(func(p *testing.PB) { for p.Next() { c.add(1) } }) if c.n != b.N { b.Fatal(c.n) }}func BenchmarkBatched(b *testing.B) { var c counter b.RunParallel(func(p *testing.PB) { n := 0 for p.Next() { n++ } c.add(n) }) if c.n != b.N { b.Fatal(c.n) }}Run go test -run=^$ -bench=. -cpu=1,2 -mutexprofile=mutex.prof -blockprofile=block.prof and inspect with go tool pprof -top mutex.prof. Shared adds lock for each operation; batched adds lock once per worker. They have the same final total but different intermediate visibility, so batching is only valid when immediate reads are unnecessary. Profile instrumentation itself adds overhead.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonCompare adjacent and separated counters
--- go.mod ---module example.test/lesson
go 1.23
--- lesson_test.go ---package lesson
import ( "sync" "sync/atomic" "testing")
type padded struct { n atomic.Int64 _ [128]byte}
func run(a, c *atomic.Int64, n int) { var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() for i := 0; i < n; i++ { a.Add(1) } }() go func() { defer wg.Done() for i := 0; i < n; i++ { c.Add(1) } }() wg.Wait()}func TestLesson(t *testing.T) { var x [2]atomic.Int64 var y [2]padded run(&x[0], &x[1], 20) run(&y[0].n, &y[1].n, 20) if x[0].Load() != 20 || x[1].Load() != 20 || y[0].n.Load() != 20 || y[1].n.Load() != 20 { t.Fatal("count") }}func BenchmarkAdjacent(b *testing.B) { var x [2]atomic.Int64; run(&x[0], &x[1], b.N) }func BenchmarkSeparated(b *testing.B) { var x [2]padded; run(&x[0].n, &x[1].n, b.N) }Each benchmark iteration count corresponds to one update on each of two counters. Compare repeated runs with -cpu=2; goroutine setup is amortized, not excluded. Padding is an illustrative spacing heuristic, not a portable cache-line size or alignment guarantee. Results depend on CPU topology, scheduling and atomic implementation. A timing difference alone cannot prove false sharing; hardware counters and controlled experiments can strengthen the explanation.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Use four workers with private counts and merge after Wait; assert final 400. Benchmark the same pattern with fixed workers. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Performance engineering 05: Analyze contention and false sharing
Check the lesson objective before moving on.
Can false sharing occur without a Go data race?
When is batching counter updates acceptable?